2015-05-19 58 views
4

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

,比如我有一个与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"}} 
    } 
} 

我需要的是寻找与所提意见的博客文章名为blog型“足球“,每个博客文章中与”足球“相匹配的评论数(在该示例中为1,因为另一评论刚刚提到”篮球“)。

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

不过看起来Elasticsearch总是返回完整的文档,所以我怎么能实现它,或者我不能?

回答

0

答案就在这里。

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

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

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

我认为这将解决这个问题