【问题标题】:ElasticSearch: returning only first result from logical groupElasticSearch:仅返回逻辑组的第一个结果
【发布时间】:2017-10-02 23:56:28
【问题描述】:

我有一个 ElasticSearch 索引,用于存储产品 - 就像在线商店一样。现在我想在我的商店中介绍产品变体,但我无法更改索引以使用一些嵌套或父/子数据类型,因为还有很多其他工具已经使用了这个索引(我不想调整这些工具还)。我们只能添加一些额外的字段。 -> 我无法在索引时间将索引和组变体重建为逻辑组。

在查询时获取此类项目组的最佳选择是什么? 另一个问题:很多产品都是非变体的,所以我的查询结果必须返回变体(分组)和非变体单独项目的混合 - 它们必须按_score一起排序。 可能的选择:没关系,如果我们没有得到一个变体组的所有项目,而只得到每个变体组的最佳结果。但我们必须确保不会将变体组的项目作为单独的搜索结果。

也许我们可以通过多个查询来实现它——比如首先对variant_id进行一些聚合,然后是另一个查询来获取所有项目

示例: 以下行已编入索引:

{"title": "Samsung TV xxx"}
{"title": "Philips TV yyy"}
{"title": "Nike shoe MyRun", "size": 40, "variant_group": 5}
{"title": "Nike shoe MyRun", "size": 42, "variant_group": 5}
{"title": "Adidas shoe YourRun", "size": 39, "variant_group": 10}
{"title": "Adidas shoe YourRun", "size": 40, "variant_group": 10}
{"title": "Adidas shoe YourRun", "size": 46, "variant_group": 10}
{"title": "Dictionary book"}

匹配所有这些项目的我的查询应该返回这些文档:

{"title": "Samsung TV xxx"}
{"title": "Philips TV yyy"}
[
    {"title": "Nike shoe MyRun", "size": 40, "variant_group": 5}
    {"title": "Nike shoe MyRun", "size": 42, "variant_group": 5}
]
[
    {"title": "Adidas shoe YourRun", "size": 39, "variant_group": 10}
    {"title": "Adidas shoe YourRun", "size": 40, "variant_group": 10}
    {"title": "Adidas shoe YourRun", "size": 46, "variant_group": 10}
    {"title": "Dictionary book"}
]
{"title": "Dictionary book"}

OR(每个变体组的最佳结果):

{"title": "Samsung TV xxx"}
{"title": "Philips TV yyy"}
{"title": "Nike shoe MyRun", "size": 40, "variant_group": 5}
{"title": "Adidas shoe YourRun", "size": 39, "variant_group": 10}
{"title": "Dictionary book"}

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    您可以将top hits sub-aggregation 与术语聚合结合使用:

    curl -XGET 'localhost:9200/your_index/products/_search&pretty' -H 'Content-Type: application/json' -d'
    {
        @@@ your filters here @@@
        "size": 0,
        "aggs": {
            "variant_groups": {
                "terms": {
                    "field": "variant_group",
                    "size": 20,
                    "missing": "No group",
                },
                "aggs": {
                    "products_hits": {
                        "top_hits": {
                            "size" : 1
                        }
                    }
                }
            }
        }
    }
    '
    

    这会根据您对每个 variant_group 的过滤器返回排名靠前的产品。

    目前仅针对基于频率的前 20 组,但可以使用术语聚合的 ordersize 参数更改顺序和大小。如果需要,您可以使用较大的尺寸值。

    missing 参数定义应如何处理缺少值的文档。默认情况下,它们将被忽略,但也可以将它们视为具有值。

    结果将在 Elasticsearch 响应的 aggregation 部分中,而不是在 hits 中,我们在查询的根中使用 size: 0 将其留空。

    【讨论】:

    • 谢谢!但是我会得到具有variant_group 的产品。没有 variant_group 的其他产品是什么情况?喜欢 {"title": "Samsung TV xxx"}
    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多