Converts a filter join into a terms query.
423000
private void convertToTermsQuery(FilterJoinNode node) {
    Map<String, Object> parent = node.getParentSourceMap();
    FilterJoinTerms terms = node.getTerms();
    BytesRef bytes = terms.getEncodedTerms();

    // Remove the filter join from the parent
    parent.remove(FilterJoinBuilder.NAME);

    // Create the nested object for the parameters of the field data terms query
    Map<String, Object> queryParams = new HashMap<>();
    queryParams.put("value", bytes.bytes);
    // use the hash of the filter join source map as cache key - see #170
    queryParams.put("_cache_key", node.getCacheId());

    // Create the nested object for the field
    Map<String, Object> field = new HashMap<>();
    field.put(node.getField(), queryParams);

    // Create the nested object for the field data terms query
    Map<String, Object> termsQuery = new HashMap<>();
    // If bytes terms encoding is used, we switch to the terms enum based terms query
    if (node.getTermsEncoding().equals(TermsByQueryRequest.TermsEncoding.BYTES)) {
      termsQuery.put(TermsEnumTermsQueryParser.NAME, field);
    }
    else {
      termsQuery.put(FieldDataTermsQueryParser.NAME, field);
    }

    // Create the object for the constant score query
    Map<String, Object> constantScoreQueryParams = new HashMap<>();
    constantScoreQueryParams.put("filter", termsQuery);

    // Add the constant score query to the parent
    parent.put(ConstantScoreQueryParser.NAME, constantScoreQueryParams);
    node.setState(FilterJoinNode.State.CONVERTED);
    this.blockingQueue.poll();
  }
743883
private FieldSearchQuery assembleFieldSearchQuery(String query, String terms) {
        if (terms != null) {
            return new FieldSearchQuery(terms);
        } else {
            try {
                return new FieldSearchQuery(Condition.getConditions(query));
            } catch (QueryParseException e) {
                throw new ValidatorProcessUsageException("Value '" + query
                        + "' of parameter '" + PARAMETER_QUERY
                        + "' is not a valid query string.");
            }
        }
    }
1036781
def _merge_model_defined_relation_wheres_to_has_query(self, has_query, relation):
        
        relation_query = relation.get_base_query()

        has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings())

        self._query.add_binding(has_query.get_query().get_bindings(), "where")
163234
def _build_search_query(self, from_date):
        

        sort = [{self._sort_on_field: {"order": "asc"}}]

        filters = []
        if self._repo:
            filters.append({"term": {"origin": self._repo}})

        if from_date:
            filters.append({"range": {self._sort_on_field: {"gte": from_date}}})

        if filters:
            query = {"bool": {"filter": filters}}
        else:
            query = {"match_all": {}}

        search_query = {
            "query": query,
            "sort": sort
        }

        return search_query
773465
function ( query, associations ) {
		_.each( associations, function ( assoc ) {
			// if the associations is to be populated with the full records...
			if ( assoc.include === "record" ) query.populate( assoc.alias );
		} );
		return query;
	}
603315
def groups_filter_from_query(query, field_map={}):
    """"""
    f = None
    # filter groups
    for group in query.get("groups", []):
        group_f = MatchAll()
        for condition in group.get("conditions", []):
            field_name = condition["field"]
            field_name = field_map.get(field_name, field_name)
            operation = condition["type"]
            values = condition["values"]
            if values:
                values = [v["value"] for v in values]
                if operation == "all":
                    # NOTE: is there a better way to express this?
                    for value in values:
                        if "." in field_name:
                            path = field_name.split(".")[0]
                            group_f &= Nested(path=path, filter=Term(**{field_name: value}))
                        else:
                            group_f &= Term(**{field_name: value})
                elif operation == "any":
                    if "." in field_name:
                        path = field_name.split(".")[0]
                        group_f &= Nested(path=path, filter=Terms(**{field_name: values}))
                    else:
                        group_f &= Terms(**{field_name: values})
                elif operation == "none":
                    if "." in field_name:
                        path = field_name.split(".")[0]
                        group_f &= ~Nested(path=path, filter=Terms(**{field_name: values}))
                    else:
                        group_f &= ~Terms(**{field_name: values})

        date_range = group.get("time")
        if date_range:
            group_f &= date_range_filter(date_range)
        if f:
            f |= group_f
        else:
            f = group_f
    return f
456186
def termLons(TERMS):
    
    res = []
    for i, sign in enumerate(SIGN_LIST):
        termList = TERMS[sign]
        res.extend([
            ID,
            sign,
            start + 30 * i,
        ] for (ID, start, end) in termList)
    return res
754254
def _expand_join(join_definition):
    
    join_table_name = join_definition.pop('table')
    join_func = getattr(mosql_query, join_definition.pop('join_type', 'join'))
    return join_func(join_table_name, **join_definition)
384802
def _in(self, *lst):
        """"""
        self.terms.append('in (%s)' % ', '.join(['"%s"' % x for x in lst]))
        return self
398687
function( terms ) {
    
    var key, document
    var result = Object.create( null )
    var self = this
    
    terms = ( terms + '' ).toLowerCase()
    terms = terms.split( /\W+/ )
    
    for( key in this.documents ) {
      
      document = this.documents[ key ]
      
      result[ key ] = terms.reduce(
        function ( value, term ) {
          return value + (
            ( document[ term ] || 0 ) * self.idf( term )
          )
        },
        0.0
      )
      
    }
    
    return result
    
  }
1311155
def apply_filters(query, args):
    
    pre_joins = []
    for querystring_key, filter_value in args.items(multi=True):
        if querystring_key in filter_registry:
            cls_inst = filter_registry[querystring_key]
            query = cls_inst.apply_filter(query, args, pre_joins)
        elif querystring_key in PaginationKeys._value_list:
            pass
        else:
            raise InvalidQueryString(querystring_key, filter_value)
    return query
338004
def search(self, query, search_fields=None):
        

        # ### DETERMINE FIELDS TO SEARCH ###

        # Use search_fields arg if given, otherwise use search_fields
        # initially configured by the manager class.
        if search_fields:
            self._search_fields = search_fields_to_dict(search_fields)
        if not self._search_fields:
            return self.none()

        # ### BUILD LIST OF TERMS TO SEARCH FOR ###

        # Remove extra spaces, put modifiers inside quoted terms.
        terms = " ".join(query.split()).replace("+ ", "+")     \
                                       .replace('+"', '"+')    \
                                       .replace("- ", "-")     \
                                       .replace('-"', '"-')    \
                                       .split('"')
        # Strip punctuation other than modifiers from terms and create
        # terms list, first from quoted terms and then remaining words.
        terms = [("" if t[0:1] not in "+-" else t[0:1]) + t.strip(punctuation)
            for t in terms[1::2] + "".join(terms[::2]).split()]
        # Remove stop words from terms that aren't quoted or use
        # modifiers, since words with these are an explicit part of
        # the search query. If doing so ends up with an empty term
        # list, then keep the stop words.
        terms_no_stopwords = [t for t in terms if t.lower() not in
            settings.STOP_WORDS]
        get_positive_terms = lambda terms: [t.lower().strip(punctuation)
            for t in terms if t[0:1] != "-"]
        positive_terms = get_positive_terms(terms_no_stopwords)
        if positive_terms:
            terms = terms_no_stopwords
        else:
            positive_terms = get_positive_terms(terms)
        # Append positive terms (those without the negative modifier)
        # to the internal list for sorting when results are iterated.
        if not positive_terms:
            return self.none()
        else:
            self._search_terms.update(positive_terms)

        # ### BUILD QUERYSET FILTER ###

        # Create the queryset combining each set of terms.
        excluded = [reduce(iand, [~Q(**{"%s__icontains" % f: t[1:]}) for f in
            self._search_fields.keys()]) for t in terms if t[0:1] == "-"]
        required = [reduce(ior, [Q(**{"%s__icontains" % f: t[1:]}) for f in
            self._search_fields.keys()]) for t in terms if t[0:1] == "+"]
        optional = [reduce(ior, [Q(**{"%s__icontains" % f: t}) for f in
            self._search_fields.keys()]) for t in terms if t[0:1] not in "+-"]
        queryset = self
        if excluded:
            queryset = queryset.filter(reduce(iand, excluded))
        if required:
            queryset = queryset.filter(reduce(iand, required))
        # Optional terms aren't relevant to the filter if there are
        # terms that are explicitly required.
        elif optional:
            queryset = queryset.filter(reduce(ior, optional))
        return queryset.distinct()
1149900
def _expand_terms(self, terms):
        
        ret = {
            'keywords': list(),
            'doc': list(),
            'from': None,
            'to': None}

        if not isinstance(terms, dict):
            stp = SearchTermParser()
            terms = stp.parse(terms, term_join=self.backend._and_join)

        if 'about' in terms:
            ret['doc'].append(terms['about'])

        if 'with' in terms:
            ret['doc'].append(terms['with'])

        if 'in' in terms:
            place_vids = self._expand_place_ids(terms['in'])
            ret['keywords'].append(place_vids)

        if 'by' in terms:
            ret['keywords'].append(terms['by'])
        ret['from'] = terms.get('from', None)
        ret['to'] = terms.get('to', None)
        return ret
1231939
def resolve(self):
        """"""
        if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_:
            value = self.value

            if isinstance(value, dict):
                value = Node(self.related_model, value, self.resource, self.related_schema).resolve()

            if '__' in self.filter_.get('name', ''):
                value = {self.filter_['name'].split('__')[1]: value}

            if isinstance(value, dict):
                return getattr(self.column, self.operator)(**value)
            else:
                return getattr(self.column, self.operator)(value)

        if 'or' in self.filter_:
            return or_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['or'])
        if 'and' in self.filter_:
            return and_(Node(self.model, filt, self.resource, self.schema).resolve() for filt in self.filter_['and'])
        if 'not' in self.filter_:
            return not_(Node(self.model, self.filter_['not'], self.resource, self.schema).resolve())
285365
def _build_filtered_query(self, f, operator):
        
        self._filtered = True
        if isinstance(f, Filter):
            filter_object = f
        else:
            filter_object = Filter(operator).filter(f)
        self._filter_dsl = filter_object
1347829
def _or_join(self, terms):
        
        from six import text_type

        if isinstance(terms, (tuple, list)):
            if len(terms) > 1:
                return ' | '.join(text_type(t) for t in terms)
            else:
                return terms[0]
        else:
            return terms
672475
def _prepare_query_term(self, field, term):
        
        if term == "*":
            return term
        add_star = False
        if term[len(term) - 1] == '*':
            add_star = True
            term = term[0 : len(term) - 1]
        term = self._escape_query_term(term)
        if add_star:
            term = '{}*'.format(term)
        if self._get_solr_type(field) in ['string', 'text', 'text_ws']:
            return '"{}"'.format(term)
        return term