一尘不染

在词条查询中具有动态列表值的elasticsearch QueryBuilder

elasticsearch

我有下面的代码,我在布尔查询中做多个必须的。在这里,我将在字段“地址”中传递必填项查询。现在,该IP地址将以其他api的列表的形式出现在我的面前,我必须将列表中的所有IP作为必填项查询传递给我。在这里,我没有办法创建QueryBuilder时如何动态传递地址值。

请提出建议。

public static SearchResponse searchResultWithAggregation(String es_index,
        String es_type, List<String> ipList, String queryRangeTime) {
        Client client = ESClientFactory.getInstance();

    QueryBuilder qb = QueryBuilders.boolQuery()
            .must(QueryBuilders.termQuery("address", "10.203.238.138"))
            .must(QueryBuilders.termQuery("address", "10.203.238.137"))
            .must(QueryBuilders.termQuery("address", "10.203.238.136"))
            .mustNot(QueryBuilders.termQuery("address", "10.203.238.140"))
            .should(QueryBuilders.termQuery("client", ""));

    queryRangeTime = "now-" + queryRangeTime + "m";
    FilterBuilder fb = FilterBuilders.rangeFilter("@timestamp")
            .from(queryRangeTime).to("now");

    SearchResponse response = client
            .prepareSearch(es_index)
            .setTypes(es_type)
            .setQuery(qb)
            .setPostFilter(fb)
            .addAggregation(
                    AggregationBuilders.avg("cpu_average").field("value"))
            .setSize(10).execute().actionGet();

    System.out.println(response.toString());
    return response;
}

阅读 575

收藏
2020-06-22

共1个答案

一尘不染

您可以使用条件查询为单个字段传递多个值。创建一个字符串数组或集合。并将其传递给条款查询。

  Set<String> address = new HashSet<String>();
  address.add("10.203.238.138");
  address.add("10.203.238.137");
  address.add("10.203.238.136");
  if(address!=null)
     QueryBuilder qb = QueryBuilders.boolQuery()
                .must(QueryBuilders.termsQuery("address",address))
                .mustNot(QueryBuilders.termQuery("address", "10.203.238.140"))
                .should(QueryBuilders.termQuery("client", ""));
  else
     QueryBuilder qb = QueryBuilders.boolQuery()
                .mustNot(QueryBuilders.termQuery("address", "10.203.238.140"))
                .should(QueryBuilders.termQuery("client", ""));

希望能帮助到你..!

2020-06-22