gpt4 book ai didi

java - 在术语查询中具有动态列表值的elasticsearch QueryBuilder

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:37 28 4
gpt4 key购买 nike

我有如下代码,我在 bool 查询中执行多个 must。在这里,我在“地址”字段中传递了必须的术语查询。现在 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;
}

最佳答案

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

  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", ""));

希望对您有所帮助...!

关于java - 在术语查询中具有动态列表值的elasticsearch QueryBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24042589/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com