Constructs a query of a single term.

        If `field_name` is not `None`, the term is search on that field only.
        If exact is `True`, the search is restricted to boolean matches.
483311
def _term_query(self, term, field_name, field_type, stemmed=True):
        
        constructor = '{prefix}{term}'

        # construct the prefix to be used.
        prefix = ''
        if field_name:
            prefix = TERM_PREFIXES['field'] + field_name.upper()
            term = _to_xapian_term(term)

        if field_name in (ID, DJANGO_ID, DJANGO_CT):
            # to ensure the value is serialized correctly.
            if field_name == DJANGO_ID:
                term = int(term)
            term = _term_to_xapian_value(term, field_type)
            return xapian.Query('%s%s' % (TERM_PREFIXES[field_name], term))

        # we construct the query dates in a slightly different way
        if field_type == 'datetime':
            date, time = term.split()
            return xapian.Query(xapian.Query.OP_AND_MAYBE,
                                constructor.format(prefix=prefix, term=date),
                                constructor.format(prefix=prefix, term=time)
                                )

        # only use stem if field is text or "None"
        if field_type not in ('text', None):
            stemmed = False

        unstemmed_term = constructor.format(prefix=prefix, term=term)
        if stemmed:
            stem = xapian.Stem(self.backend.language)
            stemmed_term = 'Z' + constructor.format(prefix=prefix, term=stem(term).decode('utf-8'))

            return xapian.Query(xapian.Query.OP_OR,
                                xapian.Query(stemmed_term),
                                xapian.Query(unstemmed_term)
                                )
        else:
            return xapian.Query(unstemmed_term)
67288
def get_true_false_both(query_params, field_name, default):
    ''''''
    valid = ('true', 'false', 'both')
    value = query_params.get(field_name, default).lower()
    if value in valid:
        return value
    v = ', '.join(sorted(valid))
    raise serializers.ValidationError({
        field_name: ['Must be one of [%s]' % v],
    })
620936
def prepareQueryTerm(self, field, term):
        
        if term == "*":
            return term
        addstar = False
        if term[len(term) - 1] == '*':
            addstar = True
            term = term[0 : len(term) - 1]
        term = self.escapeQueryTerm(term)
        if addstar:
            term = '%s*' % term
        if self.getSolrType(field) in ['string', 'text', 'text_ws']:
            return '"%s"' % term
        return term
507487
def query(self, search, query):
        
        if query:
            if self.fields:
                return search.query('multi_match', fields=self.fields, query=query)
            else:
                return search.query('multi_match', query=query)
        return search
648033
def build_db_query(fields_names, field_values):
    
    if isinstance(field_values, string_types):
        field_values = [field_values]

    if len(fields_names) != len(field_values):
        raise ValueError('Error: unable to build a primary key query due '
                         'to mismatch in number of fields {0} vs {1}'
                         .format(len(fields_names), len(field_values)))

    query = dict()
    for k, v in zip(fields_names, field_values):
        query[k] = v
    return query
444162
def _percolate_query(index, doc_type, percolator_doc_type, document):
    """"""
    if ES_VERSION[0] in (2, 5):
        results = current_search_client.percolate(
            index=index, doc_type=doc_type, allow_no_indices=True,
            ignore_unavailable=True, body={'doc': document}
        )
        return results['matches']
    elif ES_VERSION[0] == 6:
        results = current_search_client.search(
            index=index, doc_type=percolator_doc_type, allow_no_indices=True,
            ignore_unavailable=True, body={
                'query': {
                    'percolate': {
                        'field': 'query',
                        'document_type': percolator_doc_type,
                        'document': document,
                    }
                }
            }
        )
        return results['hits']['hits']
965617
def build_search(self):
        
        s = self.search()
        s = self.query(s, self._query)
        s = self.filter(s)
        if self.fields:
            s = self.highlight(s)
        s = self.sort(s)
        self.aggregate(s)
        return s
999187
def query_string(cls,
                     query,
                     default_field=None,
                     default_operator=None,
                     analyzer=None,
                     allow_leading_wildcard=None,
                     lowercase_expanded_terms=None,
                     enable_position_increments=None,
                     fuzzy_prefix_length=None,
                     fuzzy_min_sim=None,
                     phrase_slop=None,
                     boost=None,
                     analyze_wildcard=None,
                     auto_generate_phrase_queries=None,
                     minimum_should_match=None):
        '''
        
        '''
        instance = cls(query_string={'query': query})
        if default_field is not None:
            instance['query_string']['default_field'] = default_field
        if default_operator is not None:
            instance['query_string']['default_operator'] = default_operator
        if analyzer is not None:
            instance['query_string']['analyzer'] = analyzer
        if allow_leading_wildcard is not None:
            instance['query_string']['allow_leading_wildcard'] = allow_leading_wildcard
        if lowercase_expanded_terms is not None:
            instance['query_string']['lowercase_expanded_terms'] = lowercase_expanded_terms
        if enable_position_increments is not None:
            instance['query_string']['enable_position_increments'] = enable_position_increments
        if fuzzy_prefix_length is not None:
            instance['query_string']['fuzzy_prefix_length'] = fuzzy_prefix_length
        if fuzzy_min_sim is not None:
            instance['query_string']['fuzzy_min_sim'] = fuzzy_min_sim
        if phrase_slop is not None:
            instance['query_string']['phrase_slop'] = phrase_slop
        if boost is not None:
            instance['query_string']['boost'] = boost
        if analyze_wildcard is not None:
            instance['query_string']['analyze_wildcard'] = analyze_wildcard
        if auto_generate_phrase_queries is not None:
            instance['query_string']['auto_generate_phrase_queries'] = auto_generate_phrase_queries
        if minimum_should_match is not None:
            instance['query_string']['minimum_should_match'] = minimum_should_match
        return instance
343774
def find_any_field(browser, field_types, field_name):
    

    return reduce(
        operator.add,
        (find_field(browser, field_type, field_name)
         for field_type in field_types)
    )
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)
1347749
def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]:
        
        query = (
            self.query
            .filter(Account.name.like('%' + term + '%'))
            .order_by(Account.name)
        )
        # Exclude placeholder accounts?
        if not include_placeholders:
            query = query.filter(Account.placeholder == 0)

        # print(generic.get_sql(query))
        return query.all()
229454
def find(self, search_term: str) -> List[Commodity]:
        
        query = (
            self.query
            .filter(Commodity.mnemonic.like('%' + search_term + '%') |
                    Commodity.fullname.like('%' + search_term + '%'))
        )
        return query.all()
765311
def _query(options, collection_name, num_to_skip,
           num_to_return, query, field_selector, opts, check_keys):
    """"""
    encoded = _dict_to_bson(query, check_keys, opts)
    if field_selector:
        efs = _dict_to_bson(field_selector, False, opts)
    else:
        efs = b""
    max_bson_size = max(len(encoded), len(efs))
    return b"".join([
        _pack_int(options),
        _make_c_string(collection_name),
        _pack_int(num_to_skip),
        _pack_int(num_to_return),
        encoded,
        efs]), max_bson_size
1206797
def query(self, name):
        
        #log.debug('searching schema for (%s)', name)
        schema = self.schema
        wsdl = self.wsdl()
        if wsdl is None:
            qref = qualify(name, schema.root, schema.tns)
        else:
            qref = qualify(name, wsdl.root, wsdl.tns)
        query = BlindQuery(qref)
        result = query.execute(schema)
        return (result, [])
328789
def _filter_startswith(self, term, field_name, field_type, is_not):
        
        if field_type == 'text':
            if len(term.split()) == 1:
                term = '^ %s*' % term
                query = self.backend.parse_query(term)
            else:
                term = '^ %s' % term
                query = self._phrase_query(term.split(), field_name, field_type)
        else:
            term = '^%s*' % term
            query = self.backend.parse_query(term)

        if is_not:
            return xapian.Query(xapian.Query.OP_AND_NOT, self._all_query(), query)
        return query
977659
def _make_query_from_terms(self, terms):
        

        expanded_terms = self._expand_terms(terms)

        cterms = ''
        if expanded_terms['doc']:
            cterms = self.backend._or_join(expanded_terms['doc'])

        keywords = expanded_terms['keywords']

        frm_to = self._from_to_as_term(expanded_terms['from'], expanded_terms['to'])

        if frm_to:
            keywords.append(frm_to)

        if keywords:
            if cterms:
                cterms = self.backend._and_join(
                    [cterms, self.backend._field_term('keywords', expanded_terms['keywords'])])
            else:
                cterms = self.backend._field_term('keywords', expanded_terms['keywords'])

        logger.debug('partition terms conversion: `{}` terms converted to `{}` query.'.format(terms, cterms))

        return cterms
1288184
protected Query getTermQueryFilter(String field, String term) {

        return getMultiTermQueryFilter(field, term, Collections.singletonList(term));
    }