elasticsearch QueryBuilder with dynamic list value in term query

后端 未结 2 1567
南旧
南旧 2021-02-04 15:29

I have a code like below where I\'m doing multiple must in bool query. Here I\'m passing the must term queries in field \"address\". Now the ip address will come to me as a list

相关标签:
2条回答
  • 2021-02-04 15:35

    You can use the terms query to pass multiple values for single field. create a string array or set. and pass it to the terms query.

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

    Hope it helps..!

    0 讨论(0)
  • 2021-02-04 15:42

    If you use TermsQuery for address array/set, it will return any documents that match with at least one or more of the provided terms.

    List<String> address = new ArrayList<String>();
    address.add("10.203.238.138");
    address.add("10.203.238.137");
    address.add("10.203.238.136");
    
    BoolQueryBuilder qb = QueryBuilders.boolQuery();
    qb.mustNot(QueryBuilders.termQuery("address", "10.203.238.140"));
    qb.should(QueryBuilders.termQuery("client", ""));
    
    for(String add: Address){
        qb.must(QueryBuilders.termsQuery("address",add));
    }
    
    0 讨论(0)
提交回复
热议问题