2

I am trying to convert the following query to the ElasticSearch Java API:

GET /consumer/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "match": {
                  "first_name": {
                    "query": "Peter"
                  }
                }
              },
              {
                "match": {
                  "last_name": {
                    "query": "Parker"
                  }
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "match": {
                  "first_name": {
                    "query": "Parker"
                  }
                }
              },
              {
                "match": {
                  "last_name": {
                    "query": "Peter"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
} 

I tried the following :

query = QueryBuilders.boolQuery()
    .should(QueryBuilders.boolQuery()
    .must(QueryBuilders.matchQuery("first_name", "Peter").type(null))
    .must(QueryBuilders.matchQuery("last_name""Parker").type(null))
    .must(QueryBuilders.matchQuery("first_name","Parker").type(null))
    .must(QueryBuilders.matchQuery("last_name","Peter").type(null)))

I also tried :

 .should(QueryBuilders.boolQuery()
 .must(QueryBuilders.matchQuery("first_name", "Peter").type(null))
 .must(QueryBuilders.matchQuery("last_name", "Parker").type(null))
 .should(QueryBuilders.boolQuery()
 .must(QueryBuilders.matchQuery("first_name", "Parker").type(null))
 .must(QueryBuilders.matchQuery("last_name", "Peter").type(null))))

But none of them produced the same query that I created. Any idea about how I can create this?

In a few words, the first query is doing the following :

Select * from consumer where first_name='Peter' and last_name='Parker' OR first_name='Parker' and last_name='Peter'

Thank you

Yeikel
  • 854
  • 10
  • 18

1 Answers1

4

I think your second attempt was close, you need to close the first should clause. Try this

query = QueryBuilders.boolQuery()
        .should(QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery("first_name", "Peter").type(null))
            .must(QueryBuilders.matchQuery("last_name", "Parker").type(null)))
        .should(QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery("first_name", "Parker").type(null))
            .must(QueryBuilders.matchQuery("last_name", "Peter").type(null)))

You can also pass JSON string to wrapperQuery, have a look at this SO question

Community
  • 1
  • 1
ChintanShah25
  • 12,366
  • 3
  • 43
  • 44