具有多个 parent/child 关系的 Elasticsearch

Elasticsearch with multiple parent/child relationship

Book、User 和 Review 说,我正在构建一个模型复杂的应用程序。

评论包含图书和用户 ID。 为了能够搜索至少包含一篇评论的书籍,我将这本书设置为评论的父级,并设置了路由。但是,我还需要找到撰写包含某些短语的评论的用户。

是否可以将图书和用户都作为评论的父级?有没有更好的方法来处理这种情况?

请注意,我无法更改数据 modeled/not 愿意这样做的方式,因为数据是从持久性数据库传输到 Elasticsearch 的。

据我所知,您不能拥有包含两个 parents 的文档。

我的建议基于Application-side join chapter of Elasticsearch the definitive guide

  • 创建 parent/child 关系 Book/Review
  • 请确保您在 Review 映射中有 user_id 属性,其中包含撰写该评论的用户 ID。

我认为这涵盖了您描述的两种用例:

  • Books that contain at least one review 可以用 has child filter/query
  • 来解决
  • Users who wrote reviews that contain certain phrases 可以通过使用要搜索的短语查询评论并在字段 user_id 上执行 cardinality aggregation 来解决。如果您需要用户信息,您必须使用检索到的 ID 查询您的数据库(或其他弹性搜索索引)。

编辑:"give me the books that have reviews this month written by user whose name started with John"

我建议您收集所有这些高级用例并对实现它们所需的数据进行非规范化。在这种特殊情况下,将用户名反规范化为 Review 就足够了。无论如何,elasticsearch 人已经写过关于管理关系的文章 in their blog or elasticsearch the definitive guide

你有两个选择

Elasticsearch Nested Objects

Elasticsearch parent&child

两者对比评价都很好here

类似的东西(只需将 Books 类型设为 Users 和 Reviews 类型的父类)

.../index/users/_search?pretty" -d '
    {
        "query": {
            "filtered": {
                "filter": {
                    "and": [
                        {
                            "has_parent": {
                                "parent_type": "books",
                                "filter": {
                                    "has_child": {
                                        "type": "Reviews",
                                        "query": {
                                            "term": {
                                                "text_review": "some word"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
    '