add sub-aggs when building search request
190035
void addSubAggs(QueryConverter queryConverter, Aggregation agg, AggregationBuilder builder) {
        Map<String, Aggregation> aggs = agg.getAggs();
        for (String key : aggs.keySet()) {
            Aggregation subAgg = aggs.get(key);
            AbstractAggregationBuilder subBuilder = queryConverter.converterAggregation(subAgg);
            if (subBuilder != null) {
                builder.subAggregation(subBuilder);
            }
        }
    }
1327422
def searchSuggestions(query,extras)
      method = 'searchSuggestions'
      type = TODO
      args = {:query=>query}
      args[:extras] = extras if extras
      return_object type,method,args
    end
1104452
private SearchIndex makeSuggestIndex(StaplerRequest req) {
        SearchIndexBuilder builder = new SearchIndexBuilder();
        for (Ancestor a : req.getAncestors()) {
            if (a.getObject() instanceof SearchableModelObject) {
                SearchableModelObject smo = (SearchableModelObject) a.getObject();
                builder.add(smo.getSearchIndex());
            }
        }
        return builder.make();
    }
1117687
public SearchResponse searchAllWithTargetCount(String index, String type,
            AggregationBuilder[] aggregationBuilders) {
        return searchAllWithTargetCount(index, type, null, aggregationBuilders);
    }
819353
def add_query_params(self, query_params):
        '''
        '''
        query_params = as_multi_dict(query_params)
        for k in query_params:
            self.query_params.pop(k, None)
            for v in query_params.getlist(k):
                self.query_params[k] = v
        self.apply_param_schema()
        return self
582465
private void addSubQuery(BoolQueryBuilder boolQuery, Where where, QueryBuilder subQuery) {
        if(where instanceof Condition){
            Condition condition = (Condition) where;

			if (condition.isNested()) {
				boolean isNestedQuery = subQuery instanceof NestedQueryBuilder;
				InnerHitBuilder ihb = null;
				if (condition.getInnerHits() != null) {
                    try (JsonXContentParser parser = new JsonXContentParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, new JsonFactory().createParser(condition.getInnerHits()))) {
                        ihb = InnerHitBuilder.fromXContent(parser);
                    } catch (IOException e) {
                        throw new IllegalArgumentException("couldn't parse inner_hits: " + e.getMessage(), e);
                    }
                }

                // bugfix #628
                if ("missing".equalsIgnoreCase(String.valueOf(condition.getValue())) && (condition.getOpear() == Condition.OPEAR.IS || condition.getOpear() == Condition.OPEAR.EQ)) {
                    NestedQueryBuilder q = isNestedQuery ? (NestedQueryBuilder) subQuery : QueryBuilders.nestedQuery(condition.getNestedPath(), QueryBuilders.boolQuery().mustNot(subQuery), ScoreMode.None);
					if (ihb != null) {
						q.innerHit(ihb);
                    }
                    boolQuery.mustNot(q);
                    return;
                }

                if (!isNestedQuery) {
					subQuery = QueryBuilders.nestedQuery(condition.getNestedPath(), subQuery, ScoreMode.None);
				}
                if (ihb != null) {
                    ((NestedQueryBuilder) subQuery).innerHit(ihb);
                }
            } else if(condition.isChildren()) {
            	subQuery = JoinQueryBuilders.hasChildQuery(condition.getChildType(), subQuery, ScoreMode.None);
            }
        }

		//zhongshu-comment 将subQuery对象纳入到boolQuery中，即boolQuery是上一级，subQuery是下一级
		if (where.getConn() == CONN.AND) {
			boolQuery.must(subQuery);
		} else {
			boolQuery.should(subQuery);
		}
	}
576238
private function addAggregationFilters()
    {
        foreach ($this->_data as $requestName => $requestConfig) {
            if (isset($requestConfig['aggregations'])) {
                $aggregations = [];

                foreach ($requestConfig['aggregations'] as $aggName => $aggConfig) {
                    $aggregations[$aggName] = $this->replaceAggregationFilter($aggConfig);
                }

                $this->_data[$requestName]['aggregations'] = $aggregations;
            }
        }
    }
906691
def generate_search_subparser(subparsers):
    """"""
    parser = subparsers.add_parser(
        'search', description=constants.SEARCH_DESCRIPTION,
        epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter,
        help=constants.SEARCH_HELP)
    parser.set_defaults(func=search_texts)
    utils.add_common_arguments(parser)
    utils.add_db_arguments(parser)
    utils.add_corpus_arguments(parser)
    utils.add_query_arguments(parser)
    parser.add_argument('ngrams', help=constants.SEARCH_NGRAMS_HELP,
                        nargs='*', metavar='NGRAMS')
636915
def processSearch(query, tld='com', lang='en', num=10, start=0, stop=50, pause=2.0, only_standard=False):
    ''' 
        

    '''
    uriList = search(query, tld=tld, lang=lang, num=int(num), start=int(start), stop=int(stop), pause=float(pause),only_standard=only_standard)       
    
    # Dictionary containing the URI objects
    results = []
    
    # Building the objects
    for uri in uriList:
        aux = {}
        aux["type"] = "i3visio.uri"
        aux["value"] = uri        
        aux["attributes"] = []
        results.append(aux)

    return results
627994
def build(self, search, raw_query):
        
        unmatched_items = {}
        for expression, value in raw_query.items():
            # Parse query expression into tokens.
            tokens = expression.split(TOKEN_SEPARATOR)

            field = tokens[0]
            tail = tokens[1:]

            if field not in self.fields:
                unmatched_items[expression] = value
                continue

            # Map field alias to final field.
            field = self.fields_map.get(field, field)

            # Parse lookup expression. Currently only no token or a single token is allowed.
            if tail:
                if len(tail) > 1:
                    raise NotImplementedError("Nested lookup expressions are not supported")

                lookup = self.get_lookup(tail[0])
                search = lookup.apply(search, field, value)
            else:
                # Default lookup.
                custom_filter = getattr(self.custom_filter_object, 'custom_filter_{}'.format(field), None)
                if custom_filter is not None:
                    search = custom_filter(value, search)
                elif isinstance(value, list):
                    # Default is 'should' between matches. If you need anything else,
                    # a custom filter for this field should be implemented.
                    filters = [Q('match', **{field: item}) for item in value]
                    search = search.query('bool', should=filters)
                else:
                    search = search.query('match', **{field: {'query': value, 'operator': 'and'}})

        return (search, unmatched_items)
1312216
public SearchResponse searchAll(String index, String type,
            AggregationBuilder[] aggregationBuilders) {
        return searchAll(index, type, null, aggregationBuilders);
    }
1267643
private void addQueryParams(final Request request) {
        if (to != null) {
            request.addQueryParam("To", to.toString());
        }

        if (from != null) {
            request.addQueryParam("From", from.toString());
        }

        if (parentCallSid != null) {
            request.addQueryParam("ParentCallSid", parentCallSid);
        }

        if (status != null) {
            request.addQueryParam("Status", status.toString());
        }

        if (absoluteStartTime != null) {
            request.addQueryParam("StartTime", absoluteStartTime.toString(Request.QUERY_STRING_DATE_TIME_FORMAT));
        } else if (rangeStartTime != null) {
            request.addQueryDateTimeRange("StartTime", rangeStartTime);
        }

        if (absoluteEndTime != null) {
            request.addQueryParam("EndTime", absoluteEndTime.toString(Request.QUERY_STRING_DATE_TIME_FORMAT));
        } else if (rangeEndTime != null) {
            request.addQueryDateTimeRange("EndTime", rangeEndTime);
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }
1269213
function addQueryParams(req, res, next) {
  _assign(res.locals, req.params, req.query);
  next();
}
343479
public void addSubMetricQuery(final String metric_query, 
                                final int sub_query_index,
                                final int param_index) {
    if (metric_query == null || metric_query.isEmpty()) {
      throw new IllegalArgumentException("Metric query cannot be null or empty");
    }
    if (sub_query_index < 0) {
      throw new IllegalArgumentException("Sub query index must be 0 or greater");
    }
    if (param_index < 0) {
      throw new IllegalArgumentException("Parameter index must be 0 or greater");
    }
    if (sub_metric_queries == null) {
      sub_metric_queries = Maps.newHashMap();
    }
    sub_metric_queries.put(sub_query_index, metric_query);
    parameter_index.put(param_index, Parameter.METRIC_QUERY);
  }
1261783
function buildUrlSearch(query) {

  function buildParam(key) {
    let value = query[key];
    if (value === null || value === undefined) value = '';
    else value = encodeURIComponent(value);
    return `${key}=${value}`;
  }

  return keys(query) . map(buildParam) . join('&');
}
143116
def get_agg(self):
        
        """ Returns an aggregated value """
        query = self.get_query(False)
        res = self.get_metrics_data(query)
        # We need to extract the data from the JSON res
        # If we have agg data use it
        agg_id = str(ElasticQuery.AGGREGATION_ID)
        if 'aggregations' in res and 'values' in res['aggregations'][agg_id]:
            if self.AGG_TYPE == 'median':
                agg = res['aggregations'][agg_id]['values']["50.0"]
                if agg == 'NaN':
                    # ES returns NaN. Convert to None for matplotlib graph
                    agg = None
            else:
                raise RuntimeError("Multivalue aggregation result not supported")
        elif 'aggregations' in res and 'value' in res['aggregations'][agg_id]:
            agg = res['aggregations'][agg_id]['value']
        else:
            agg = res['hits']['total']

        return agg
789099
public function constructQuery($source, $query, $aggs, $post_query, $settings) {
        $query_data = [
            'ignore_unavailable' => true,
        ];
        $query_body = [
            'size' => 100,
        ];
        $meta = [
            'aggs' => [],
            'flatten' => true,
            'map' => [],
            'scroll' => false,
            'post_query' => false,
            'count' => false,
        ];

        $from = Util::get($settings, 'from', time());
        $to = Util::get($settings, 'to', time());
        $date_field = Util::get($settings, 'date_field');

        // Construct filter query clauses.
        $filter_data = $this->constructFilter($source, $query, $date_field, $from, $to);
        if(!is_null($filter_data)) {
            $query_body['query'] = [
                'bool' => [
                    'filter' => $filter_data
                ]
            ];
        }

        // Set index.
        if(Util::exists($settings, 'index')) {
            $query_data['index'] = $settings['index'];

            if(Util::get($settings, 'date_based', false)) {
                $query_data['index'] = implode(',', Util::generateDateIndices($query_data['index'], Util::get($settings, 'date_interval'), $from, $to));
            }
        }

        // Construct agg queries clauses.
        $agg_data = $this->constructAggs($aggs);

        // Construct setting data.
        if(!is_null($agg_data)) {
            $query_body['aggs'] = $agg_data;
            // When executing an agg, we don't care about the actual hits.
            $query_body['size'] = 0;
            $meta['aggs'] = $aggs;
        }
        if(array_key_exists('count', $settings)) {
            $meta['count'] = (bool) $settings['count'];

            // Same thing if we want a count and have no aggs or post query.
            if(is_null($post_query)) {
                $query_body['size'] = 0;
            }
        }
        if(array_key_exists('flatten', $settings)) {
            $meta['flatten'] = (bool) $settings['flatten'];
        }
        if(array_key_exists('map', $settings)) {
            $meta['map'] = (array) $settings['map'];
        }
        if(!is_null($post_query)) {
            $meta['post_query'] = true;
        }
        // Determine whether to use a scroll query, which is more efficient.
        /*
        if(...) {
            $meta['scroll'] = true;
        }
         */

        // Construct setting clauses.
        $query_body = array_merge($query_body, $this->constructSettings($settings));

        $query_data['body'] = $query_body;

        return [$query_data, $meta];
    }