对 Elasticsearch 文档中的嵌套字段进行排序

问题描述 投票:0回答:1

我有一个看起来像这样的文档

{
    "screeningDate": "2024-06-10T00:02:08+02:00",
    "nbPortfolios": 3,
    "portfolios":
    [
        {
            "name": "XYZ",
        },
        {
            "name": "123",
        },
        {
            "name": "ABC",
        }
    ]
}

我想按字母顺序对搜索结果中的

portfolios
字段进行排序,以便获得

{
    "screeningDate": "2024-06-10T00:02:08+02:00",
    "nbPortfolios": 3,
    "portfolios":
    [
        {
            "name": "123",
        },
        {
            "name": "ABC",
        },
        {
            "name": "XYZ",
        }
    ]
}

这是我尝试过的

{
  "sort": [
    {
      "portfolios.label": {
        "order": "desc",
        "nested": {
          "path": "portfolios"
        }
      }
    }
  ],
…
}

还有

…
{
    "nested":
    {
        "path": "portfolios.name",
        "query":
        {
            "bool":
            {
                "must":
                [
                    {
                        "query_string":
                        {
                            "query": "test",
                        }
                    }
                ]
            }
        },
        "inner_hits":
        {
            "sort":
            [
                {
                    "portfolios.label":
                    {
                        "order": "asc"
                    }
                }
            ]
        }
    }
}
…

但是子文档没有排序。

sorting elasticsearch nested
1个回答
0
投票

您可以使用inner_hits解决方案,但响应与您所排除的有点不同。

推荐方式:

在索引过程中对数据进行排序,然后进行搜索。

POST /_bulk?pipeline=sort_portfolios
{"index":{"_index":"portfolios_index","_id":"1"}}
{"screeningDate":"2024-06-10T00:02:08+02:00","nbPortfolios":3,"portfolios":[{"name":"XYZ"},{"name":"123"},{"name":"ABC"}]}

PUT /_ingest/pipeline/sort_portfolios
{
  "processors": [
    {
      "script": {
        "source": """
          if (ctx.portfolios != null) {
            ctx.portfolios.sort((a, b) -> {
              return a.name.compareTo(b.name);
            });
          }
        """
      }
    }
  ]
}

GET portfolios_index/_search

enter image description here

自动化:

  • 要自动使用摄取管道,您可以将
    index.default_pipeline
    设置放入索引设置中。
  • 对于现有数据使用
    POST portfolios_index/_update_by_query?pipeline=sort_portfolios
© www.soinside.com 2019 - 2024. All rights reserved.