elasticsearch,包含field1或field2中数据的文档

时间:2015-07-22 14:41:20

标签: elasticsearch

如何指示elasticsearch返回包含以下某个字段的所有文档:['field1','field2']?

我试过了:

{
'query': {
    'bool':{
        'must':[
            'multi_match':{
                'fields':['field1','field2'],
                     'operator':'AND',
                     'tie_breaker':1.0,
                     'query': '*',
                     'type':'cross_fields'
                 }
             ]
         }
     }
}

我也尝试过:

{
    "query":{
        "wildcard":
            {
                 "field1":"*"
            }
        }
}

有效,但是:

{
    "query":{
        "wildcard":
            {
                 "field*":"*"
            }
        }
}

没有

1 个答案:

答案 0 :(得分:1)

您可以使用exists

中的两个bool filter过滤器执行此操作

作为一个例子,我设置了一个简单的索引并给它一些数据:

PUT /test_index

POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"field1":"foo","field2":"bar"}
{"index":{"_id":2}}
{"field2":"foo","field3":"bar"}
{"index":{"_id":3}}
{"field3":"foo","field4":"bar"}
{"index":{"_id":4}}
{"field4":"foo","field5":"bar"}

如果我想查找所有包含"field1"或"field3",我可以这样做:

POST /test_index/_search
{
   "query": {
      "filtered": {
         "query": {
            "match_all": {}
         },
         "filter": {
            "bool": {
               "should": [
                  { "exists": { "field": "field1" } },
                  { "exists": { "field": "field3" } }
               ]
            }
         }
      }
   }
}

它返回我的期望:

{
   "took": 1,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 3,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "1",
            "_score": 1,
            "_source": {
               "field1": "foo",
               "field2": "bar"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "2",
            "_score": 1,
            "_source": {
               "field2": "foo",
               "field3": "bar"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "3",
            "_score": 1,
            "_source": {
               "field3": "foo",
               "field4": "bar"
            }
         }
      ]
   }
}

这是我使用的代码:

http://sense.qbox.io/gist/991b828de250e5125fd372bf7e6b066acec55fcd