Elasticsearch-在查询中将数组作为参数传递

时间:2018-11-27 20:38:29

标签: java elasticsearch

我正在尝试使用数组作为查询参数在Elasticsearch中进行查询。例如,我要在“水果”字段中搜索[苹果,橙子,菠萝]。但就我而言,我想搜索一个companyIds数组。我想到了这个查询:

{  
   "query":{  
      "bool":{  
         "must":[  
            {  
               "range":{  
                  "eventconnected":{  
                     "from":"2018-11-21T15:00:00.023Z",
                     "to":"2018-11-22T15:00:00.023Z",
                     "include_lower":true,
                     "include_upper":true,
                     "boost":1.0
                  }
               }
            },
            {  
               "match":{  
                  "idunity":{  
                     "query":[  
                        "157",
                        "160"
                     ],
                     "operator":"OR",
                     "prefix_length":0,
                     "max_expansions":50,
                     "fuzzy_transpositions":true,
                     "lenient":false,
                     "zero_terms_query":"NONE",
                     "auto_generate_synonyms_phrase_query":true,
                     "boost":1.0
                  }
               }
            }
         ],
         "adjust_pure_negative":true,
         "boost":1.0
      }
   }
}

运行此查询时,出现以下错误:

{"error":{"root_cause":[{"type":"parsing_exception","reason":"[match] unknown token [START_ARRAY] after [query]","line":20,"col":30}],"type":"parsing_exception","reason":"[match] unknown token [START_ARRAY] after [query]","line":20,"col":30},"status":400}

就好像我无法将数组作为查询的参数传递一样。所以我的问题是:在ElasticSearch中将数组作为查询的参数传递的正确方法是什么?

要提供更多上下文:我正在Java项目中执行此操作,此查询的searchSourceBuilder如下: locaisTemp是我要作为参数传递的数组。

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders
                    .boolQuery()
                        .must(QueryBuilders
                            .rangeQuery("eventconnected")
                                .from(tempDate0.getTime())
                                .to(tempDate.getTime()))
                        .must(QueryBuilders
                                .matchQuery("idunity", locaisTemp)) 
                    ); 

1 个答案:

答案 0 :(得分:3)

使用termsQuery代替,而且您应该使用filter()代替must(),因为您只是在过滤:

                    ...
                    .filter(QueryBuilders
                       ^    .termsQuery("idunity", locaisTemp))
                       |         ^ 
                       |         |
                       change this 
                    ...