Add an es_dsl query object to the es_dsl Search object

        :param key_val: a key-value pair(dict) containing the query to be added to the search object
        :returns: self, which allows the method to be chainable with the other methods
323788
def add_query(self, key_val={}):
        

        q = Q("match", **key_val)
        self.search = self.search.query(q)
        return self
431226
def match(self, query_dict=None, **query):
        
        if query_dict:
            self._q.append({'$match': query_dict})
        else:
            self._q.append({'$match': query})
        return self
59511
function (key, value) {
            var self = this, _queryMap;
            parseQuery(self);
            _queryMap = self._queryMap;
            if (typeof key === 'string') {
                self._queryMap[key] = value;
            } else {
                if (key instanceof Query) {
                    key = key.get();
                }
                S.each(key, function (v, k) {
                    _queryMap[k] = v;
                });
            }
            return self;
        }
686164
public Request query(String key, Object value) {
        this.query.put(key, value);
        return this;
    }
453081
def expand_query(config, kwds):
    
    pattern = []
    for query in kwds.pop('pattern', []):
        expansion = config.search.alias.get(query)
        if expansion is None:
            pattern.append(query)
        else:
            parser = SafeArgumentParser()
            search_add_arguments(parser)
            ns = parser.parse_args(expansion)
            for (key, value) in vars(ns).items():
                if isinstance(value, (list, tuple)):
                    if not kwds.get(key):
                        kwds[key] = value
                    else:
                        kwds[key].extend(value)
                else:
                    kwds[key] = value
    kwds['pattern'] = pattern
    return config.search.kwds_adapter(kwds)
111012
public static QueryRequest query(String key, Object value) {
        return QueryRequest.create().addParameter(key, value);
    }
178803
def add(self, key, value):
        '''
        
        '''
        if key in self.reserved_keys:
            raise Exception('You cannot add the key %s directly, use %s' % (key, self.reserved_keys[key]))
        if isinstance(value, Report):
            self._sub_reports[key] = value
            self._data_fields['sub_reports'].append(key)
        else:
            self._data_fields[key] = value
147712
def matches_query(self, key, query):
        
        dumped = query.dump()
        dumped['className'] = query._query_class._class_name
        self._add_condition(key, '$inQuery', dumped)
        return self
691898
def query(self, *args, **kwargs):
        
        clone = self._clone()
        queries = []
        from pyes.query import Query

        if args:
            for f in args:
                if isinstance(f, Query):
                    queries.append(f)
                else:
                    raise TypeError('Only Query objects can be passed as argument')

        for field, value in kwargs.items():
            if value == [None]:
                value = ["$$$$"]
            queries.append(self._build_inner_query(field, value))

        clone._queries.extend(queries)
        return clone
923720
def search(self, query, indices=None, doc_types=None, model=None, scan=False, headers=None, **query_params):
        
        if isinstance(query, Search):
            search = query
        elif isinstance(query, (Query, dict)):
            search = Search(query)
        else:
            raise InvalidQuery("search() must be supplied with a Search or Query object, or a dict")

        if scan:
            query_params.setdefault("search_type", "scan")
            query_params.setdefault("scroll", "10m")

        return ResultSet(self, search, indices=indices, doc_types=doc_types,
                         model=model, query_params=query_params, headers=headers)
857256
def query(key, value=None, service=None, profile=None):  # pylint: disable=W0613
    '''
    
    '''
    comps = key.split('?')
    key = comps[0]
    key_vars = {}
    for pair in comps[1].split('&'):
        pair_key, pair_val = pair.split('=')
        key_vars[pair_key] = pair_val

    renderer = __opts__.get('renderer', 'jinja|yaml')
    rend = salt.loader.render(__opts__, {})
    blacklist = __opts__.get('renderer_blacklist')
    whitelist = __opts__.get('renderer_whitelist')
    url = compile_template(
        ':string:',
        rend,
        renderer,
        blacklist,
        whitelist,
        input_data=profile[key]['url'],
        **key_vars
    )

    extras = {}
    for item in profile[key]:
        if item not in ('backend', 'url'):
            extras[item] = profile[key][item]

    result = http.query(
        url,
        decode=True,
        **extras
    )

    return result['dict']
619039
def search(self, keyword):
        
        params = {
            "source": "map",
            "description": keyword
        }
        data = self._request(ENDPOINTS['SEARCH'], params)
        data['result_data'] = [res for res in data['result_data'] if isinstance(res, dict)]
        return data
278174
def price_query_filter(price_query_dict):
    
    if not isinstance(price_query_dict, dict):
        raise TypeError("dict_list is not a list. Please try again")
    required = ["period", "exchange"]
    pkeys = price_query_dict.keys()
    for r in required:
        if r not in pkeys:
            raise KeyError("An important key is not available {}".format(r))
    return True
346793
def add_api_key(key, value):
    

    if key is None or key == "":
        logger.error("Key cannot be empty")

    if value is None or value == "":
        logger.error("Value cannot be empty")

    from .. import datatools
    data = datatools.get_data()

    if "keys" not in data["discord"]:
        data["discord"]["keys"] = {}

    is_key_new = False
    if key not in data["discord"]["keys"]:
        is_key_new = True
    elif data["discord"]["keys"][key] == value:
        logger.info("API key '{}' already has value '{}'".format(key, value))
        return

    data["discord"]["keys"][key] = value
    datatools.write_data(data)

    key_text = "added" if is_key_new else "updated"
    logger.info("API key '{}' {} with value '{}'".format(key, key_text, value))
1256856
def build_q(fields_dict, params_dict, request=None):
    
    # Building search query
    # queries generated by different search_fields are ANDed
    # if a search field is defined for more than one field, are put together with OR
    and_query = Q()

    for fieldname in fields_dict:
        search_field = fields_dict[fieldname]
        if fieldname in params_dict and params_dict[fieldname] != '' and params_dict[fieldname] != []:
            or_query = None

            if type(search_field) == type(list()):
                field_list = search_field
                search_operator = "__icontains"
                fixed_filters = None
                multiple_values = False
                custom_query_method = None
                value_mapper = None

            else: # dictionary of field definitions
                if search_field.get('ignore', False):
                    continue

                field_list = search_field['fields']
                search_operator = search_field.get('operator', None)
                fixed_filters = search_field.get('fixed_filters', None)
                multiple_values = search_field.get('multiple', False)
                custom_query_method =  search_field.get('custom_query', None)
                value_mapper =  search_field.get('value_mapper', None)

            for model_field in field_list:

                if multiple_values:
                    if hasattr(params_dict, "getlist"):
                        request_field_value = params_dict.getlist(fieldname)
                    elif type(params_dict[fieldname]) == list:
                        request_field_value = params_dict[fieldname]
                    else:
                        request_field_value = [params_dict[fieldname]]
                    if value_mapper:
                        request_field_value = [value_mapper(value) for value in request_field_value]
                else:
                    request_field_value = params_dict[fieldname] if not value_mapper else value_mapper(params_dict[fieldname])

                if not custom_query_method:
                    fieldname_key = model_field + search_operator
                    filter_dict = { fieldname_key : request_field_value}
                    if not or_query:
                        or_query = Q(**filter_dict)
                    else:
                        or_query = or_query | Q(**filter_dict)
                else:
                    #TODO: this is a hack for using request data in custom_query
                    #it would be better to pass ALSO the request to custom_query_method
                    if not request:
                        cf = custom_query_method(model_field, request_field_value, params_dict)
                    else:
                        cf = custom_query_method(model_field, request_field_value, request)

                    if not or_query:
                        or_query = cf
                    else:
                        or_query = or_query | cf

            #fixed_filters
            fixed_filters_q = Q()
            #fixed_filters must return a Q object or None
            if fixed_filters:
                if callable(fixed_filters):
                    fixed_filters_q = fixed_filters(params_dict)
                elif type(fixed_filters) is dict:
                    fixed_filters_q = Q(**fixed_filters)

            and_query = and_query & or_query
            and_query = and_query & fixed_filters_q


    return and_query
356493
def add_predicate(self, key, value, predicate_type='equals'):
        
        if predicate_type not in operators:
            predicate_type = operator_lkup.get(predicate_type)
        if predicate_type:
            self.predicates.append({'type': predicate_type,
                                    'key': key,
                                    'value': value
                                    })
        else:
            raise Exception("predicate type not a valid operator")
1267172
function (callback, term, from, size, sort, specs, ids, brands, categories, prices, dsl) {
        var host = apiSearch
        // proxy will pass XGET
        // var method = 'POST'
        var endpoint = '/items.json'
        var body

        if (typeof dsl === 'object' && dsl !== null) {
          // custom Query DSL
          // must be a valid search request body
          // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-body.html
          body = dsl
        } else {
          /*
          // term is required
          if (typeof term !== 'string') {
            msg = 'Search term is required and must be a string'
            errorHandling(callback, msg)
            return
          }
          */

          // handle results sorting
          var order = [
            {
              'available': {
                'order': 'desc'
              }
            },
            {
              'ad_relevance': {
                'order': 'desc'
              }
            },
            '_score'
          ]

          // defines most common sorting options
          switch (sort) {
            case 1:
              // sort by sales after relevance
              order.splice(2, 0, {
                'sales': {
                  'order': 'desc'
                }
              })
              break

            case 2:
              // sort by price
              // lowest price -> highest price
              order.splice(1, 0, {
                'price': {
                  'order': 'asc'
                }
              })
              break

            case 3:
              // sort by price
              // highest price -> lowest price
              order.splice(1, 0, {
                'price': {
                  'order': 'desc'
                }
              })
              break

            default:
              // default sort by views after preseted sorting options
              order.push({
                'views': {
                  'order': 'desc'
                }
              })
          }

          body = {
            'query': {
              'bool': {
                // condition, only visible products
                'filter': [
                  {
                    'term': {
                      'visible': true
                    }
                  }
                ]
              }
            },
            'sort': order,
            'aggs': {
              'brands': {
                'terms': {
                  'field': 'brands.name'
                }
              },
              'categories': {
                'terms': {
                  'field': 'categories.name'
                }
              },
              // ref.: https://github.com/elastic/elasticsearch/issues/5789
              'specs': {
                'nested': {
                  'path': 'specs'
                },
                'aggs': {
                  'grid': {
                    'terms': {
                      'field': 'specs.grid',
                      'size': 30
                    },
                    'aggs': {
                      'text': {
                        'terms': {
                          'field': 'specs.text'
                        }
                      }
                    }
                  }
                }
              },
              // Metric Aggregations
              'min_price': {
                'min': {
                  'field': 'price'
                }
              },
              'max_price': {
                'max': {
                  'field': 'price'
                }
              },
              'avg_price': {
                'avg': {
                  'field': 'price'
                }
              }
            }
          }

          // search term
          if (typeof term === 'string') {
            // https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html
            body.query.bool.must = {
              'multi_match': {
                'query': term,
                'fields': [
                  'name',
                  'keywords'
                ]
              }
            }

            // handle terms suggestion
            // 'did you mean?'
            // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html
            body.suggest = {
              'text': term,
              'words': {
                'term': {
                  'field': 'name'
                }
              }
            }
          }

          // pagination
          // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html
          if (typeof from === 'number' && from > 0) {
            // offset
            body.from = from
          }
          if (typeof size === 'number' && size > 0) {
            // limit
            body.size = size
          } else {
            // default page size
            body.size = 24
          }

          // filters
          if (typeof specs === 'object' && specs !== null && Object.keys(specs).length > 0) {
            // nested ELS object
            // http://nocf-www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html
            for (var key in specs) {
              if (Array.isArray(specs[key]) && specs[key].length > 0) {
                // add filter
                body.query.bool.filter.push({
                  'nested': {
                    'path': 'specs',
                    'query': {
                      'bool': {
                        'filter': [
                          {
                            'term': {
                              'specs.grid': key
                            }
                          }, {
                            'terms': {
                              'specs.text': specs[key]
                            }
                          }
                        ]
                      }
                    }
                  }
                })
              }
            }
          }

          if (Array.isArray(ids) && ids.length > 0) {
            // add filter
            // search by product Object IDs
            body.query.bool.filter.push({
              'terms': {
                '_id': ids
              }
            })
          }

          // handle filter by categories and brands with IDs or names
          var filterFields = {
            'brands': brands,
            'categories': categories
          }
          for (var field in filterFields) {
            var filterVal = filterFields[field]
            if (Array.isArray(filterVal) && filterVal.length > 0) {
              if (/^[a-f0-9]{24}$/.test(filterVal[0])) {
                // filtering by ObjectID
                field += '._id'
              } else {
                // filtering by name
                field += '.name'
              }

              // add filter
              var filterObj = { 'terms': {} }
              filterObj.terms[field] = filterVal
              body.query.bool.filter.push(filterObj)
            }
          }

          // price ranges
          if (typeof prices === 'object' && prices !== null && Object.keys(prices).length > 0) {
            var rangeQuery = {
              'range': {
                'price': {}
              }
            }
            if (typeof prices.min === 'number' && !isNaN(prices.min)) {
              rangeQuery.range.price.gte = prices.min
            }
            if (typeof prices.max === 'number' && !isNaN(prices.max)) {
              rangeQuery.range.price.lte = prices.max
            }

            // add filter
            body.query.bool.filter.push(rangeQuery)
          }
        }

        /*
        msg = logHeader('INFO') +
          '\nQuery DSL' +
          '\n' + JSON.stringify(body)
        logger.log(msg)
        */
        runMethod(callback, endpoint, host, body)
      }