Build a queryset matching words in the given search query,
        treating quoted terms as exact phrases and taking into
        account + and - symbols as modifiers controlling which terms
        to require and exclude.
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()
220827
function queryMatchesAfterIncluding(matches, includeClause) {
  if (!includeClause) {
    return matches;
  }

  const includeClauses = includeClause.split(',');
  matches = _.map(matches, match => {
    for (let i = 0; i < includeClauses.length; i++) {
      const paths = includeClauses[i].split('.');
      match = includePaths(match, paths);
    }
    return match;
  });

  return matches;
}
30030
def match(pattern, sentence, *args, **kwargs):
    
    return compile(pattern, *args, **kwargs).match(sentence)
529030
def query=(search_term)
      @search_term =
        case search_term
        when nil, ''        then []
        when String, Symbol then [search_term]
        when Array          then search_term.flatten.select { |e| [String, Symbol].include? e.class }
        else fail ArgumentError, 'search_term must be a String, Symbol or Array. ' \
                                 "#{ search_term.inspect } given."
        end

      build_query
    end
690519
def search(query)
      regex = Regexp.new(query, 'i')
      _cookbooks.collect do |_, v|
        v[v.keys.first] if regex.match(v[v.keys.first].name)
      end.compact
    end
601751
def filter_query(s):
    
    matches = re.findall(r'(?:"([^"]*)")|([^"]*)', s)
    result_quoted = [t[0].strip() for t in matches if t[0]]
    result_unquoted = [t[1].strip() for t in matches if t[1]]
    return result_quoted, result_unquoted
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.");
            }
        }
    }
475364
private String queryAsString(Map<String, Object> query) {
        ArrayList<String> queryParts = new ArrayList<String>(query.size());
        for(Map.Entry<String, Object> entry : query.entrySet()) {
            String value = this.encodeQueryParameter(entry.getValue().toString());
            String key = this.encodeQueryParameter(entry.getKey());
            String term = String.format("%s=%s", key, value);
            queryParts.add(term);
        }
        return Misc.join("&", queryParts);
    }
1038649
function compactGraphQLQuery (query) {
    let lexer = new Tokenizr()

    /*  configure lexical analysis  */
    lexer.rule(/#[^\r\n]*(?=\r?\n)/,                       (ctx, match) => { ctx.accept("comment") })
    lexer.rule(/"(?:\\"|[^"])*"/,                          (ctx, match) => { ctx.accept("string") })
    lexer.rule(/$[a-zA-Z_][a-zA-Z0-9_]*/,                  (ctx, match) => { ctx.accept("var") })
    lexer.rule(/[a-zA-Z_][a-zA-Z0-9_]*/,                   (ctx, match) => { ctx.accept("id") })
    lexer.rule(/[+-]?[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/, (ctx, match) => { ctx.accept("number") })
    lexer.rule(/[ \t\r\n]+/,                               (ctx, match) => { ctx.accept("ws", " ") })
    lexer.rule(/[{}]/,                                     (ctx, match) => { ctx.accept("brace") })
    lexer.rule(/[[\]]/,                                    (ctx, match) => { ctx.accept("bracket") })
    lexer.rule(/[()]/,                                     (ctx, match) => { ctx.accept("parenthesis") })
    lexer.rule(/,/,                                        (ctx, match) => { ctx.accept("comma") })
    lexer.rule(/!/,                                        (ctx, match) => { ctx.accept("not") })
    lexer.rule(/\.\.\./,                                   (ctx, match) => { ctx.accept("ellipsis") })
    lexer.rule(/@/,                                        (ctx, match) => { ctx.accept("at") })
    lexer.rule(/:/,                                        (ctx, match) => { ctx.accept("colon") })
    lexer.rule(/./,                                        (ctx, match) => { ctx.accept("any") })
    lexer.input(query)
    lexer.debug(false)

    /*  fetch all parsed tokens  */
    let tokens = lexer.tokens()

    /*  remove whitespace tokens at harmless positions  */
    let output = ""
    let re = /^(?:brace|bracket|parenthesis|comma|colon)$/
    for (let i = 0; i < tokens.length; i++) {
        if (   tokens[i].type === "comment"
            || (   tokens[i].type === "ws"
                && (   (   i < tokens.length - 1
                        && tokens[i + 1].type.match(re))
                    || (    i > 0
                        && tokens[i - 1].type.match(re))))) {
            tokens.splice(i, 1)
            i--
        }
    }

    /*  assembly and return new query string  */
    tokens.forEach((token) => {
        output += token.value
    })
    return output
}
199697
def tokenize_query(query: str) -> Dict[str, Iterable]:
    
    expressions = split_query(query)
    name_operation_tuples = [parse_expression(expression) for expression in expressions]
    operation_by_name = defaultdict(list)
    for name, operation in name_operation_tuples:
        operation_by_name[name].append(operation)
    return operation_by_name
1358934
def derive_queryset(self, **kwargs):
        
        # get our parent queryset
        queryset = super(SmartListView, self).get_queryset(**kwargs)

        # apply any filtering
        search_fields = self.derive_search_fields()
        search_query = self.request.GET.get('search')
        if search_fields and search_query:
            term_queries = []
            for term in search_query.split(' '):
                field_queries = []
                for field in search_fields:
                    field_queries.append(Q(**{field: term}))
                term_queries.append(reduce(operator.or_, field_queries))

            queryset = queryset.filter(reduce(operator.and_, term_queries))

        # add any select related
        related = self.derive_select_related()
        if related:
            queryset = queryset.select_related(*related)

        # return our queryset
        return queryset
164032
def search_for(self, query, include_draft=False):
        
        query = query.lower()
        if not query:
            return []

        def contains_query_keyword(post_or_page):
            contains = query in post_or_page.title.lower() \
                       or query in Markup(
                get_parser(post_or_page.format).parse_whole(
                    post_or_page.raw_content)
            ).striptags().lower()
            return contains

        return filter(contains_query_keyword,
                      chain(self.get_posts(include_draft=include_draft),
                            self.get_pages(include_draft=include_draft)
                            if current_app.config[
                                'ALLOW_SEARCH_PAGES'] else []))
323788
def add_query(self, key_val={}):
        

        q = Q("match", **key_val)
        self.search = self.search.query(q)
        return self
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
1008793
def normalize_query(query_string,
                    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
                    normspace=re.compile(r'\s{2,}').sub):
    

    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
1169775
def _term(self, term):
        
        # All terms must be strings for Elasticsearch
        term = str(term)
        if term:
            self.__query["q"] += term
        return self
857244
def refine(query, description):
    

    for attribute, arguments in description.items():
        if hasattr(query, attribute):
            attribute = getattr(query, attribute)
        else:
            raise ValueError("Unknown query method: " + attribute)

        # query descriptions are often automatically generated, and
        # may include empty calls, which we skip
        if utils.isempty(arguments):
            continue

        if callable(attribute):
            method = attribute
            if isinstance(arguments, dict):
                query = method(**arguments)
            elif isinstance(arguments, list):
                query = method(*arguments)
            else:
                query = method(arguments)
        else:
            setattr(attribute, arguments)

    return query