Exemplo n.º 1
0
    /**
     * Override default `toJSON` to return DSL representation for `sort` parameter.
     *
     * @override
     * @returns {Object|string} returns an Object which maps to the elasticsearch query DSL
     */
    toJSON() {
        const geoPointIsNil = isNil(this._geoPoint);
        const scriptIsNil = isNil(this._script);

        if (geoPointIsNil && scriptIsNil) {
            if (isEmpty(this._opts)) return this._field;

            if (
                Object.keys(this._opts).length === 1 &&
                has(this._opts, 'order')
            ) {
                return { [this._field]: this._opts.order };
            }
        }

        let repr;

        // Should I pick only the accepted properties here?
        if (!geoPointIsNil) {
            repr = {
                _geo_distance: Object.assign(
                    { [this._field]: this._geoPoint },
                    this._opts
                )
            };
        } else if (!scriptIsNil) {
            repr = {
                _script: Object.assign({ script: this._script }, this._opts)
            };
        } else {
            repr = { [this._field]: this._opts };
        }

        return recursiveToJSON(repr);
    }
    // eslint-disable-next-line require-jsdoc
    constructor(field, docType) {
        super('percolate');

        if (!isNil(field)) this._queryOpts.field = field;
        // Delegate this to method:
        if (!isNil(docType)) this._queryOpts.document_type = docType;
    }
Exemplo n.º 3
0
  /**
   * @param {string} consumer - the consumer name
   * @param {string} provider - the provider name
   * @param {number} port - the mock service port, defaults to 1234
   * @param {string} host - the mock service host, defaults to 127.0.0.1
   */
  constructor (consumer, provider, port = 1234, host = '127.0.0.1', ssl = false) {
    if (isNil(consumer) || isNil(provider)) {
      throw new Error('Please provide the names of the provider and consumer for this Pact.')
    }
    if (isNil(port)) {
      throw new Error('Please provide the port to connect to the Pact Mock Server.')
    }

    this._request = new Request()
    this._baseURL = `${ssl ? 'https' : 'http'}://${host}:${port}`
    this._pactDetails = {
      consumer: { name: consumer },
      provider: { name: provider }
    }
  }
    /**
     * Override default `toJSON` to return DSL representation for the request body search
     *
     * @override
     * @returns {Object} returns an Object which maps to the elasticsearch query DSL
     */
    toJSON() {
        const dsl = recursiveToJSON(this._body);

        if (!isEmpty(this._aggs)) dsl.aggs = recMerge(this._aggs);

        if (!isEmpty(this._suggests) || !isNil(this._suggestText)) {
            dsl.suggest = recMerge(this._suggests);

            if (!isNil(this._suggestText)) {
                dsl.suggest.text = this._suggestText;
            }
        }

        return dsl;
    }
    // eslint-disable-next-line require-jsdoc
    constructor(name, aggType, refUrl, bucketsPath) {
        super(name, aggType);

        this._refUrl = refUrl;

        if (!isNil(bucketsPath)) this._aggsDef.buckets_path = bucketsPath;
    }
Exemplo n.º 6
0
 /**
  * Check the instance for object representation of Geo Point.
  * If representation is null, new object is initialised.
  * If it is not null, warning is logged and point is overwritten.
  * @private
  */
 _checkObjRepr() {
     if (isNil(this._point)) this._point = {};
     else if (!isObject(this._point)) {
         this._warnMixedRepr();
         this._point = {};
     }
 }
Exemplo n.º 7
0
    /**
     * Sets the Geo Point value expressed as an object,
     * with `lat` and `lon` keys.
     *
     * @param {Object} point
     * @returns {GeoPoint} returns `this` so that calls can be chained
     * @throws {TypeError} If `point` is not an instance of object
     */
    object(point) {
        checkType(point, Object);

        !isNil(this._point) && this._warnMixedRepr();

        this._point = point;
        return this; // This doesn't make much sense. What else are you gonna call?
    }
Exemplo n.º 8
0
    // eslint-disable-next-line require-jsdoc
    constructor(queryType, field) {
        super(queryType);

        this._field = null;
        this._fieldOpts = {};

        if (!isNil(field)) this._field = field;
    }
Exemplo n.º 9
0
    // eslint-disable-next-line require-jsdoc
    constructor(field, order) {
        this._field = field;

        this._opts = {};
        this._geoPoint = null;
        this._script = null;

        if (!isNil(order)) this.order(order);
    }
    /**
     * Sets the moving average weighting model that we wish to use. Optional.
     *
     * @example
     * const agg = esb.movingAverageAggregation('the_movavg', 'the_sum')
     *     .model('simple')
     *     .window(30);
     *
     * @example
     * const agg = esb.movingAverageAggregation('the_movavg', 'the_sum')
     *     .model('ewma')
     *     .window(30)
     *     .settings({ alpha: 0.8 });
     *
     * @param {string} model Can be `simple`, `linear`,
     * `ewma` (aka "single-exponential"), `holt` (aka "double exponential")
     * or `holt_winters` (aka "triple exponential").
     * Default is `simple`
     * @returns {MovingAverageAggregation} returns `this` so that calls can be chained
     */
    model(model) {
        if (isNil(model)) invalidModelParam(model);

        const modelLower = model.toLowerCase();
        if (!MODEL_SET.has(modelLower)) invalidModelParam(model);

        this._aggsDef.model = modelLower;
        return this;
    }
    /**
     * Sets the distance calculation mode, `arc` or `plane`.
     * The `arc` calculation is the more accurate.
     * The `plane` is the faster but least accurate.
     *
     * @example
     * const agg = esb.geoDistanceAggregation('rings_around_amsterdam', 'location')
     *     .origin(esb.geoPoint().string('52.3760, 4.894'))
     *     .unit('km')
     *     .distanceType('plane')
     *     .ranges([{ to: 100 }, { from: 100, to: 300 }, { from: 300 }]);
     *
     * @param {string} type
     * @returns {GeoDistanceAggregation} returns `this` so that calls can be chained
     * @throws {Error} If `type` is neither `plane` nor `arc`.
     */
    distanceType(type) {
        if (isNil(type)) invalidDistanceTypeParam(type);

        const typeLower = type.toLowerCase();
        if (typeLower !== 'plane' && typeLower !== 'arc')
            invalidDistanceTypeParam(type);

        this._aggsDef.distance_type = typeLower;
        return this;
    }
Exemplo n.º 12
0
    /**
     * Sets the relationship between Query and indexed data
     * that will be used to determine if a Document should be matched or not.
     *
     * @param {string} relation Can be one of `WITHIN`, `CONTAINS`, `DISJOINT`
     * or `INTERSECTS`(default)
     * @returns {GeoShapeQuery} returns `this` so that calls can be chained
     */
    relation(relation) {
        if (isNil(relation)) invalidRelationParam(relation);

        const relationUpper = relation.toUpperCase();
        if (!GEO_RELATION_SET.has(relationUpper)) {
            invalidRelationParam(relation);
        }

        this._fieldOpts.relation = relationUpper;
        return this;
    }
Exemplo n.º 13
0
    /**
     * Sets the suggest mode which controls what suggestions are included
     * or controls for what suggest text terms, suggestions should be suggested.
     *
     * Three possible values can be specified:
     *   - `missing`: Only provide suggestions for suggest text terms that
     *     are not in the index. This is the default.
     *   - `popular`:  Only suggest suggestions that occur in more docs
     *     than the original suggest text term.
     *   - `always`: Suggest any matching suggestions based on terms in the suggest text.
     *
     * @param {string} mode Can be `missing`, `popular` or `always`
     * @returns {TermSuggester} returns `this` so that calls can be chained.
     * @throws {Error} If `mode` is not one of `missing`, `popular` or `always`.
     */
    suggestMode(mode) {
        if (isNil(mode)) invalidSuggestModeParam(mode);

        const modeLower = mode.toLowerCase();
        if (!SUGGEST_MODE_SET.has(modeLower)) {
            invalidSuggestModeParam(mode);
        }

        this._suggestOpts.suggest_mode = modeLower;
        return this;
    }
Exemplo n.º 14
0
    /**
     * Sets the string distance implementation to use for comparing how similar
     * suggested terms are.
     *
     * Five possible values can be specified:
     *   - `internal`: The default based on `damerau_levenshtein` but highly optimized for
     *     comparing string distance for terms inside the index.
     *   - `damerau_levenshtein`: String distance algorithm based on Damerau-Levenshtein
     *     algorithm.
     *   - `levenstein`: String distance algorithm based on Levenstein edit distance
     *     algorithm.
     *   - `jarowinkler`: String distance algorithm based on Jaro-Winkler algorithm.
     *   - `ngram`: String distance algorithm based on character n-grams.
     *
     * @param {string} implMethod One of `internal`, `damerau_levenshtein`, `levenstein`,
     * `jarowinkler`, `ngram`
     * @returns {TermSuggester} returns `this` so that calls can be chained.
     * @throws {Error} If `implMethod` is not one of `internal`, `damerau_levenshtein`,
     * `levenstein`, `jarowinkler` or ngram`.
     */
    stringDistance(implMethod) {
        if (isNil(implMethod)) invalidStringDistanceParam(implMethod);

        const implMethodLower = implMethod.toLowerCase();
        if (!STRING_DISTANCE_SET.has(implMethodLower)) {
            invalidStringDistanceParam(implMethod);
        }

        this._suggestOpts.string_distance = implMethodLower;
        return this;
    }
Exemplo n.º 15
0
    /**
     * Set order for sorting. The order defaults to `desc` when sorting on the `_score`,
     * and defaults to `asc` when sorting on anything else.
     *
     * @param {string} order The `order` option can have the following values.
     * `asc`, `desc` to sort in ascending, descending order respectively.
     * @returns {Sort} returns `this` so that calls can be chained.
     */
    order(order) {
        if (isNil(order)) invalidOrderParam(order);

        const orderLower = order.toLowerCase();
        if (orderLower !== 'asc' && orderLower !== 'desc') {
            invalidOrderParam(order);
        }

        this._opts.order = orderLower;
        return this;
    }
Exemplo n.º 16
0
    /**
     * Elasticsearch supports sorting by array or multi-valued fields.
     * The `mode` option controls what array value is picked for sorting the
     * document it belongs to.
     *
     * The `mode` option can have the following values:
     *
     * - `min` - Pick the lowest value.
     * - `max` - Pick the highest value.
     * - `sum` - Use the sum of all values as sort value.
     *   Only applicable for number based array fields.
     * - `avg` - Use the average of all values as sort value.
     *   Only applicable for number based array fields.
     * - `median` - Use the median of all values as sort value.
     *   Only applicable for number based array fields.
     *
     * @example
     * const sort = esb.sort('price', 'asc').mode('avg');
     *
     * @param {string} mode One of `avg`, `min`, `max`, `sum` and `median`.
     * @returns {Sort} returns `this` so that calls can be chained.
     */
    mode(mode) {
        if (isNil(mode)) invalidModeParam(mode);

        const modeLower = mode.toLowerCase();
        if (!SORT_MODE_SET.has(modeLower)) {
            invalidModeParam(mode);
        }

        this._opts.mode = modeLower;
        return this;
    }
    /**
     * Set policy for missing data. Optional.
     *
     * [Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline.html#gap-policy)
     *
     * @param {string} policy Can be `skip` or `insert_zeros`
     * @returns {PipelineAggregationBase} returns `this` so that calls can be chained
     */
    gapPolicy(policy) {
        if (isNil(policy)) invalidGapPolicyParam(policy, this._refUrl);

        const policyLower = policy.toLowerCase();
        if (policyLower !== 'skip' && policyLower !== 'insert_zeros') {
            invalidGapPolicyParam(policy, this._refUrl);
        }

        this._aggsDef.gap_policy = policyLower;
        return this;
    }
Exemplo n.º 18
0
    /**
     * Sets the sort to control how suggestions should be sorted per
     * suggest text term.
     *
     * Two possible values:
     *   - `score`: Sort by score first, then document frequency and
     *     then the term itself.
     *   - `frequency`: Sort by document frequency first, then similarity
     *     score and then the term itself.
     *
     * @param {string} sort Can be `score` or `frequency`
     * @returns {TermSuggester} returns `this` so that calls can be chained.
     * @throws {Error} If `sort` is neither `score` nor `frequency`.
     */
    sort(sort) {
        if (isNil(sort)) invalidSortParam(sort);

        const sortLower = sort.toLowerCase();
        if (sortLower !== 'score' && sortLower !== 'frequency') {
            invalidSortParam(sort);
        }

        this._suggestOpts.sort = sortLower;
        return this;
    }
    /**
     * This setting can influence the management of the values used
     * for de-duplication. Each option will hold up to shard_size
     * values in memory while performing de-duplication but
     * the type of value held can be controlled
     *
     * @param {string} hint the possible values are `map`, `global_ordinals`,
     * `global_ordinals_hash` and `global_ordinals_low_cardinality`
     * @returns {DiversifiedSamplerAggregation} returns `this` so that calls can be chained
     * @throws {Error} If Execution Hint is outside the accepted set.
     */
    executionHint(hint) {
        if (isNil(hint)) invalidExecutionHintParam(hint);

        const hintLower = hint.toLowerCase();
        if (!EXECUTION_HINT_SET.has(hintLower)) {
            invalidExecutionHintParam(hint);
        }

        this._aggsDef.execution_hint = hintLower;
        return this;
    }
    /**
     * Allows to collapse search results based on field values. The collapsing
     * is done by selecting only the top sorted document per collapse key.
     *
     * The field used for collapsing must be a single valued `keyword` or `numeric`
     * field with `doc_values` activated
     *
     * @example
     * const reqBody = esb.requestBodySearch()
     *     .query(esb.matchQuery('message', 'elasticsearch'))
     *     .collapse('user')
     *     .sort(esb.sort('likes'))
     *     .from(10);
     *
     * @example
     * // Expand each collapsed top hits with the `inner_hits` option:
     * const reqBody = esb.requestBodySearch()
     *     .query(esb.matchQuery('message', 'elasticsearch'))
     *     .collapse(
     *         'user',
     *         esb.innerHits('last_tweets')
     *             .size(5)
     *             .sort(esb.sort('date', 'asc')),
     *         4
     *     )
     *     .sort(esb.sort('likes'))
     *     .from(10);
     *
     * @param {string} field
     * @param {InnerHits=} innerHits Allows to expand each collapsed top hits.
     * @param {number=} maxConcurrentGroupRequests The number of concurrent
     * requests allowed to retrieve the inner_hits' per group
     * @returns {RequestBodySearch} returns `this` so that calls can be chained.
     * @throws {TypeError} If `innerHits` is not an instance of `InnerHits`
     */
    collapse(field, innerHits, maxConcurrentGroupRequests) {
        const collapse = (this._body.collapse = { field });

        if (!isNil(innerHits)) {
            checkType(innerHits, InnerHits);

            collapse.inner_hits = innerHits;
            collapse.max_concurrent_group_searches = maxConcurrentGroupRequests;
        }

        return this;
    }
Exemplo n.º 21
0
exports.checkType = function checkType(instance, type) {
    if (!(instance instanceof type)) {
        if (isNil(instance)) {
            console.warn(
                `Was expecting instance of ${type.name} but got ${instance}!`
            );
        } else
            console.warn(
                `${inspect(instance)} is of the type ${typeof instance}`
            );

        throw new TypeError(`Argument must be an instance of ${type.name}`);
    }
};
Exemplo n.º 22
0
    /**
     * Sets the `validation_method` parameter. Can be set to `IGNORE_MALFORMED` to accept
     * geo points with invalid latitude or longitude, `COERCE` to try and infer correct latitude
     * or longitude, or `STRICT` (default is `STRICT`).
     *
     * Note: The `ignore_malformed` and `coerce` parameters have been removed
     * from `geo_bounding_box`, `geo_polygon`, and `geo_distance` queries in
     * elasticsearch 6.0.
     *
     * @param {string} method One of `IGNORE_MALFORMED`, `COERCE` or `STRICT`(default)
     * @returns {GeoQueryBase} returns `this` so that calls can be chained.
     * @throws {Error} If `method` parameter is not one of `IGNORE_MALFORMED`, `COERCE` or `STRICT`
     */
    validationMethod(method) {
        if (isNil(method)) invalidValidationMethod(method);

        const methodUpper = method.toUpperCase();
        if (
            methodUpper !== 'IGNORE_MALFORMED' &&
            methodUpper !== 'COERCE' &&
            methodUpper !== 'STRICT'
        ) {
            invalidValidationMethod(method);
        }

        this._queryOpts.validation_method = methodUpper;
        return this;
    }
    /**
     * Set the decay mode.
     *
     * @param {string} mode  Can be one of `linear`, `exp`, and `gauss`.
     * Defaults to `gauss`.
     * @returns {DecayScoreFunction} returns `this` so that calls can be chained.
     */
    mode(mode) {
        if (isNil(mode)) invalidModeParam(mode);

        const modeLower = mode.toLowerCase();
        if (
            modeLower !== 'linear' &&
            modeLower !== 'exp' &&
            modeLower !== 'gauss'
        ) {
            invalidModeParam(mode);
        }

        this._name = mode;
        return this;
    }
Exemplo n.º 24
0
  return async (dispatch, getState) => {
    const { skipass: searchSkipass } = getState().get('searchSkipass').toJS()

    dispatch(removeStoredSkipassRequest())

    try {
      await removeSkipass(skipass)
      dispatch(removeStoredSkipassSuccess(skipass))

      if (!isNil(searchSkipass) && searchSkipass.cardNumber === skipass.cardNumber) {
        dispatch(toggleSkipassCanBeAdded(true))
      }
    } catch (e) {
      dispatch(removeStoredSkipassFailure(e))
    }
  }
    /**
     * Sets the ordering for buckets
     *
     * @example
     * const agg = esb.histogramAggregation('prices', 'price', 50)
     *     .order('_count', 'desc');
     *
     * @example
     * const agg = esb.histogramAggregation('prices', 'price', 50)
     *     .order('promoted_products>rating_stats.avg', 'desc')
     *     .agg(
     *         esb.filterAggregation('promoted_products')
     *             .filter(esb.termQuery('promoted', 'true'))
     *             .agg(esb.statsAggregation('rating_stats', 'rating'))
     *     );
     *
     * @param {string} key
     * @param {string} direction `asc` or `desc`
     * @returns {HistogramAggregationBase} returns `this` so that calls can be chained
     */
    order(key, direction = 'desc') {
        if (isNil(direction)) invalidDirectionParam(direction);

        const directionLower = direction.toLowerCase();
        if (directionLower !== 'asc' && directionLower !== 'desc') {
            invalidDirectionParam(direction);
        }

        if (has(this._aggsDef, 'order')) {
            if (!Array.isArray(this._aggsDef.order)) {
                this._aggsDef.order = [this._aggsDef.order];
            }

            this._aggsDef.order.push({ [key]: directionLower });
        } else {
            this._aggsDef.order = { [key]: directionLower };
        }

        return this;
    }
    // eslint-disable-next-line require-jsdoc
    constructor(name, path) {
        super(name, 'nested');

        if (!isNil(path)) this._aggsDef.path = path;
    }
    // eslint-disable-next-line require-jsdoc
    constructor(script) {
        super('script_score');

        if (!isNil(script)) this._opts.script = script;
    }
Exemplo n.º 28
0
    // This is extremely similar to ValueTermQueryBase
    // Maybe rename, move and reuse it?

    // eslint-disable-next-line require-jsdoc
    constructor(field, value) {
        super('span_term');

        if (!isNil(field)) this._field = field;
        if (!isNil(value)) this._queryOpts.value = value;
    }
Exemplo n.º 29
0
    // eslint-disable-next-line require-jsdoc
    constructor(field) {
        super('exists');

        if (!isNil(field)) this._queryOpts.field = field;
    }
Exemplo n.º 30
0
       break
     case '1.5':
       result = Math.ceil(1 / getters.getSquareLengthHeight) + Math.ceil(1 / getters.getSquareWidthHeight)
       break
     case '2':
       result = (Math.ceil(1 / getters.getSquareWidthHeight)) * 2
       break
     case '2.5':
       result = Math.ceil(1 / getters.getSquareLengthHeight) + (Math.ceil(1 / getters.getSquareWidthHeight)) * 2
       break
   }
   result = (getters.getAreaCommon - getters.getAreaOpening) * result
   return result
 },
 getAreaCommon (state, getters) {
   if (isNil(state.building.length) && isNil(state.building.width) && isNil(state.building.height)) {
     return null
   }
   const result = ((toNumber(state.building.length) + toNumber(state.building.width)) * 2) * toNumber(state.building.height)
   return result
 },
 getAreaOpening (state) {
   return state.opening.reduce((total, currentIndex) => {
     return total + isEmpty(currentIndex.width) * isEmpty(currentIndex.height)
   }, 0)
 },
 checkCommonLess (state, getters) {
   const common = getters.getAreaCommon === null ? 0 : getters.getAreaCommon
   if (common !== 0 && common / 2 <= getters.getAreaOpening) {
     if (i18n.locale === state.language.primary) {
       state.openingText = 'Площадь проемов не должна превышать общую площадь строения'