从Elasticsearch中的索引中仅获取过滤的嵌套对象 [英] Fetch only filtered nested objects from index in elasticsearch

查看:123
本文介绍了从Elasticsearch中的索引中仅获取过滤的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含嵌套对象的文档,如下所示:

I have a document with nested objects, something like this:

{
    "title" : "Title 1",
    "books": [{
        "book_title": "b title 1",
        "year": 2014
    }, {
        "book_title": "b title 2",
        "year": 2015
    }]
}

现在,我需要按书名(不是book_title)和年份(比如说2014)过滤书籍。我需要的输出将是:

Now I need to filter the books on by title (not book_title) and year (let's say 2014). The output I need will be:

{
    "title" : "Title 1",
    "books": [{
        "book_title": "b title 1",
        "year": 2014
    }]
}

当我使用嵌套过滤器时,即使它们不匹配,我也会得到所有嵌套对象。我如何只获取匹配的嵌套对象?

When I use a nested filter I get all the nested objects even if they don't match. How can I fetch only the matched nested objects?

推荐答案

您需要使用嵌套 inner_hits 功能如下。

You need to use the nested inner_hits feature like below.

{
  "_source": [
    "title"
  ],
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "title 1"
          }
        },
        {
          "nested": {
            "path": "books",
            "query": {
              "term": {
                "books.year": 2014
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  }
}

在输出中,您将准确获得所需的内容,即 title 字段和嵌套的 books 数组中的匹配图书。

In the output you'll get exactly what you expect, namely the title field and the matching book from the nested books array.

这篇关于从Elasticsearch中的索引中仅获取过滤的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆