2016-10-03 53 views
1

我想下面的查詢轉換爲ElasticSearch的Java API: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" 
        } 
       } 
       } 
      ] 
      } 
     } 
     ] 
    } 
    } 
} 

我試過如下:

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))) 

我也試過:

.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)))) 

但是他們都沒有生成我創建的相同查詢。任何關於如何創建這個的想法?

幾句話,第一個查詢執行以下操作:

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

謝謝

回答

2

我覺得你的第二次嘗試靠近,你需要關閉首先應該子句。試試這個

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))) 

你也可以傳遞JSON字符串wrapperQuery,看看this SO質疑