1

Let's say I have a index in elasticsearch with two fields: title and tags. I have few documents there

  1. Should be returned by query

    { title: "My main title on this page", tags: ["first", "whatever"] }
    
  2. Should not be returned by query

    { title: "My on this page", tags: ["first", "page", "whatever"] }
    
  3. Should be returned by query

    { title: "My main title on this page", tags: ["page", "whatever"]}
    

I want to find all documents which title CONTAINS "main title" AND tag "first" OR "page". I want to use java API for this, but I'm not sure how can I do this. I know that I can use filter query to create "or" and "and". Not sure how can I add to query the title part, and how can I get the logic with "at least one from the list".

Any ideas?

1 Answer 1

1

It depends whether you care about the order of the "main" and "title" words (is it a phrase), but this is relatively simple:

{
  "query" : {
    "bool" : {
      "must" : [
        {
          "match_phrase" : {
            "title" : "main title"
          }
        },
        {
          "terms" : {
            "tags" : [ "first", "page" ]
          }
        }
      ]
    }
  }
}

By default, the terms query is going to work as a single match and it will boost the score (relevancy) by matching multiple tags. This will perform an exact match, which you should only do with not_analyzed strings. Anything with in the must will inherently behave like an AND; you can understand the bool query/filter by checking here. This translates pretty simply into the Java API:

import static org.elasticsearch.index.query.QueryBuilders.*;

SearchResponse response =
    client.prepareSearch("your-index").setTypes("your-type")
          .setQuery(
               boolQuery()
                   .must(matchPhraseQuery("title", "main title"))
                   .must(termsQuery("tags", "first", "page"))
          .execute()
          .actionGet();
Sign up to request clarification or add additional context in comments.

Comments

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.