【问题标题】:Sort an elasicsearch resultset based on a filter term根据过滤条件对弹性搜索结果集进行排序
【发布时间】:2013-11-28 14:49:14
【问题描述】:

对于电子商务,我正在实施弹性搜索,以便获得一个类别的产品 ID 的排序和分页结果集。

我有一个如下所示的产品文档:

PUT /products_test/product/1
{
  "id": "1",
  "title": "foobar",
  "sort": 102,
  "categories": [
                  "28554568",
                  "28554577",
                  "28554578"
  ],
}

为了得到结果集,我过滤和排序如下:

POST /products/_search
{
    "filter": {
        "term": {
         "categories": "28554666"
        }
    },
    "sort" : [
        { "sort" : {"order" : "asc"}}
    ]
}

但是,我现在了解到的要求是,产品分类取决于类别。查看上面的示例,这意味着我需要为类别数组中的每个值添加不同的排序值,并且根据我过滤的类别,我想按相应的排序值进行排序。

文档应如下所示:

PUT /products_test/product/1
{
  "id": "1",
  "title": "foobar",
  "categories": [
    { "id": "28554568", "sort": "102" },
    { "id": "28554577", "sort": "482" },
    { "id": "28554578", "sort": "2" }
  ]
}

我的查询现在应该可以排序如下:

POST /products/_search
{
    "filter": {
        "term": {
         "categories.id": "28554666"
        }
    },
    "sort" : [
        { "categories.{filtered_category_id}.sort" : {"order" : "asc"}}
    ]
}

有没有可能做到这一点?

【问题讨论】:

    标签: sorting elasticsearch


    【解决方案1】:

    为此,您必须将类别存储为嵌套文档。否则,Elasticsearch 将不知道什么类别与什么类别 ID 相关联。

    然后,您必须对嵌套文档进行排序,同时通过过滤来选择正确的文档。

    这是一个您可以使用的可运行示例:https://www.found.no/play/gist/47282a07414e1432de6d

    curl -XPUT "$ELASTICSEARCH_ENDPOINT/play" -d '{
        "mappings": {
            "type": {
                "properties": {
                    "categories": {
                        "type": "nested"
                    }
                }
            }
        }
    }'
    
    
    curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '
    {"index":{"_index":"play","_type":"type"}}
    {"id":1,"title":"foobar","categories":[{"id":"28554568","sort":102},{"id":"28554577","sort":482},{"id":"28554578","sort":2}]}
    {"index":{"_index":"play","_type":"type"}}
    {"id":2,"title":"barbaz","categories":[{"id":"28554577","sort":0}]}
    '
    
    curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
    {
        "query": {
            "nested": {
                "path": "categories",
                "query": {
                    "term": {
                        "categories.id": {
                            "value": 28554577
                        }
                    }
                }
            }
        },
        "sort": {
            "categories.sort": {
                "order": "asc",
                "nested_filter": {
                    "term": {
                        "categories.id": 28554577
                    }
                }
            }
        }
    }
    '
    

    【讨论】:

    • 非常感谢!这就是我一直在寻找的答案。
    猜你喜欢
    • 2021-11-19
    • 2019-08-07
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多