【问题标题】:May Elasticsearch nested query return only matched nested documents for nested fields?Elasticsearch 嵌套查询可以只返回嵌套字段的匹配嵌套文档吗?
【发布时间】:2019-10-29 23:38:15
【问题描述】:

我是 Elasticsearch 的新手,提出了一个问题,即 Elasticsearch 嵌套查询是否可能只返回嵌套字段的匹配嵌套文档。

例如,我有一个名为 blog 的类型,其中包含一个名为 comments 的嵌套字段

{
  "id": 1,
  ...
  "comments":[
    {"content":"Michael is a basketball player"},
    {"content":"David is a soccer player"}
  ]
}
{
  "id": 2,
  ...
  "comments":[
    {"content":"Wayne is a soccer player"},
    {"content":"Steven is also a soccer player"},
  ]
}

和嵌套查询

{"query":{
  "nested":{
    "path":"comments",
    "query":{"match":{"comments.content":"soccer"}}
  }
}

我需要的是搜索带有提到“足球”的 cmets 的博客文章,并为每篇博客文章搜索匹配“足球”的 cmets 计数(在示例中它计数为 1,因为另一条评论刚刚提到“篮球”) .

{"hits":[
  {
    "id":1,
    ...
    "count_for_comments_that_matches_query":1,
  },
  {
    "id":2,
    ...
    "count_for_comments_that_matches_query":2,
  }
]}

但是,Elasticsearch 似乎总是返回完整的文档,那么我该如何实现它,或者我不能呢?

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    答案就在这里。

    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-inner-hits.html#nested-inner-hits

    您需要使用 Elastic 搜索的 nested inner hits 功能。

    {
       "_source": [
          "id"
       ],
       "query": {
          "bool": {
             "must": [
                {
                   "match": {
                      "id": "1"
                   }
                },
                {
                   "nested": {
                      "path": "comments",
                      "query": {
                         "match": {
                            "comments.content": "soccer"
                         }
                      },
                      "inner_hits": {}
                   }
                }
             ]
          }
       }
    }
    

    我认为它会解决问题

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多