2016-10-03 50 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质疑