0

Under an index, I have my documents with fields lets say name and location. Now, to search all documents with name "Peter" and location "Paris".

My Java code for this is:

SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder builder = new SearchSourceBuilder().postFilter(QueryBuilders.termQuery("name", "Peter")).postFilter(QueryBuilders.termQuery("location", "Paris"));

SearchResponse response = null;
    try {
        response = client.search(searchRequest, RequestOptions.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    }

Above code, doesn't give me accurate result. Could someone please help with correct approach ?

1
  • I had added the JAVA API example, did you get a chance to go through it?? Commented Dec 6, 2020 at 8:43

2 Answers 2

1

You can use the below code, note currently you are using the term query on text field, which will not allow you to do the case-insensitive match as it's not analyzed and normally used for exact searches.

SearchRequest searchRequest = new SearchRequest("index-name");
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (name != null) {
            MatchQueryBuilder nameMatchQueryBuilder = new MatchQueryBuilder("name", name); // replace name with `peter`
            boolQueryBuilder.should(nameMatchQueryBuilder); // change it to `must` if you want this result to be present.
        }
        if (location != null) {
            MatchQueryBuilder locationMatchQueryBuilder = new MatchQueryBuilder("location", location);
            boolQueryBuilder.should(locationMatchQueryBuilder);
        }
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQueryBuilder);
        log.info("Search json {}", searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = esclient.search(searchRequest, RequestOptions.DEFAULT);

Also please notice the comments in the code, as you can see it generates boolean query, so if you want both terms to be present replace boolQueryBuilder.should(nameMatchQueryBuilder); construct with boolQueryBuilder.must(nameMatchQueryBuilder);

Sign up to request clarification or add additional context in comments.

Comments

0

In JSON format, your query should be like this :

{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "Peter"
          }
        },
        {
          "match": {
            "location": "Paris"
          }
        }
      ]
    }
  }
}

1 Comment

Thank you for the reply. How would I do that in Java API ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.