ElasticSearch查询子对象

时间:2015-07-14 13:29:11

标签: elasticsearch

我今天经常浏览文档,但无法找到答案;可能是因为我是Elastic的新手并且还没有真正了解整个ES术语。

假设我有books类型,其中包含一堆好书。每本书都有一个嵌套的作者。

{
  "name": "Me and Jane",
  "rating": "10",
  "author": {
    "name": "John Doe",
    "alias":"Mark Twain"
  }
}

现在,我知道我们可以像这样查询作者字段:

"match": {
   "author.name": "Doe"
 }

但是如果我想搜索所有作者字段呢?我尝试了author._all,但这并不起作用。

2 个答案:

答案 0 :(得分:0)

您可以使用Query String Query,例如:

 {
     "query": {
         "query_string": {
             "fields": ["author.*"],
             "query": "doe",
             "use_dis_max": true
         }
     }
 }

答案 1 :(得分:0)

另一种方法是multi_match,带有通配符字段名称:https://www.elastic.co/guide/en/elasticsearch/guide/current/multi-match-query.html#_using_wildcards_in_field_names

这样的事情,我想:

  "query": {
    "nested": {
      "path": "author",
      "query": {
        "multi_match": {
          "query": "doe",
          "fields": [
            "author.*"
          ]
        }
      }
    }
  }

更新:提供完整样本

PUT /books
{
  "mappings": {
    "paper": {
      "properties": {
        "author": {
          "type": "nested",
          "properties": {
            "name": {
              "type": "string"
            },
            "alias": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

POST /books/paper/_bulk
{"index":{"_id":1}}
{"author":[{"name":"john doe","alias":"doe"},{"name":"mark twain","alias":"twain"}]}
{"index":{"_id":2}}
{"author":[{"name":"mark doe","alias":"john"}]}
{"index":{"_id":3}}
{"author":[{"name":"whatever","alias":"whatever"}]}

GET /books/paper/_search
{
  "query": {
    "nested": {
      "path": "author",
      "query": {
        "multi_match": {
          "query": "john",
          "fields": [
            "author.*"
          ]
        }
      }
    }
  }
}

结果是:

   "hits": {
      "total": 2,
      "max_score": 0.5906161,
      "hits": [
         {
            "_index": "books",
            "_type": "paper",
            "_id": "2",
            "_score": 0.5906161,
            "_source": {
               "author": [
                  {
                     "name": "mark doe",
                     "alias": "john"
                  }
               ]
            }
         },
         {
            "_index": "books",
            "_type": "paper",
            "_id": "1",
            "_score": 0.5882852,
            "_source": {
               "author": [
                  {
                     "name": "john doe",
                     "alias": "doe"
                  },
                  {
                     "name": "mark twain",
                     "alias": "twain"
                  }
               ]
            }
         }
      ]
   }