简体   繁体   中英

Elasticsearch java api for full text search with filters

I want to do a full text search on string "user" which can match any feild in my document and then apply filter so that i get only records where the value of x feild is either "abc" or "xyz".

Fiddling with Sense , the below request fulfills my requirement.

GET _search
{
   "query":{
      "filtered":{
         "query":{
             "query_string": {
                 "query": "user"
         }
         },
         "filter":
             [

                    {"term": { "x": "abc"}},
                     {"term": { "x": "xyz"}}              
            ]    
      }
   }
}

But, i want a java api to do the above stuff. I have searched the elastic documentation and the SO , but have not found what i am looking for as api like QueryBuilders.filteredQuery seems deprecated . I am currently using 2.3.4 but can upgrade.

Elasticsearch 2.x java Api doesn't have implementation for filtered query. According to the elasticsearch documentation, they suggest to use the bool query instead with a must clause for the query and a filter clause for the filter.

In java you could create a method to create a wrapper method for the filtered query. This would be like:

   public static QueryBuilder filteredQuery(QueryBuilder query, QueryBuilder filter){
        BoolQueryBuilder filteredQuery = QueryBuilders.boolQuery().must(query);
        return filteredQuery.filter(filter);

    }

where,

QueryBuilder query = QueryBuilders.queryStringQuery("user");
QueryBuilder filter = QueryBuilders.boolQuery().filter(QueryBuilders.boolQuery().should(QueryBuilders.termsQuery("x", "abc", "xyz")));

This query is equivalent to the one mentioned above. Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM