Elastic Search 根据字段对搜索结果进行分组

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

您好,我想根据特定字段对弹性搜索查询结果进行分组。我已经阅读了折叠和聚合文档,但找不到如何实现这一点。 这是一个例子 假设我有三个文件:-

  {
"id":"1"
"sub":"1_1a"
"name" : "TV",
"make" : "samsung",
"model":"plasma"}

{
"id":"2"
"subid":"1_2a"
"name" : "TV",
"make" : "samsung",
"model":"plasma_different_model"}

{
"id":"3"
"subid":"1_3a"
"name" : "TV",
"make" : "samsung",
"model":"plasma_another_different_model"}

我想按 subid 对查询结果进行分组,仅将 sub-id="1" 的第一部分与下划线分开。

所以我的目标是根据相关性仅获取一个“sub-id”=“1”的文档作为搜索结果。 我怎样才能实现这个目标?

elasticsearch kibana elastic-stack opensearch
1个回答
0
投票

您可以通过此类查询中的运行时字段来完成

GET /runtime_field_with_split/_search?filter_path=hits.hits
{
  "runtime_mappings": {
    "subid_prefix": {
      "type": "keyword",
      "script": """
        String[] subParts = /_/.split(doc['subid.keyword'].value);
        emit(subParts[0]);
      """
    }
  },
  "query": {
    "term": {
      "subid_prefix": "1"
    }
  },
  "fields": ["subid_prefix"]
}

回应

{
  "hits" : {
    "hits" : [
      {
        "_index" : "runtime_field_with_split",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "id" : "1",
          "subid" : "1_1a",
          "name" : "TV",
          "make" : "samsung",
          "model" : "plasma"
        },
        "fields" : {
          "subid_prefix" : [
            "1"
          ]
        }
      },
      {
        "_index" : "runtime_field_with_split",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "id" : "2",
          "subid" : "1_2a",
          "name" : "TV",
          "make" : "samsung",
          "model" : "plasma_different_model"
        },
        "fields" : {
          "subid_prefix" : [
            "1"
          ]
        }
      },
      {
        "_index" : "runtime_field_with_split",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : 1.0,
        "_source" : {
          "id" : "3",
          "subid" : "1_3a",
          "name" : "TV",
          "make" : "samsung",
          "model" : "plasma_another_different_model"
        },
        "fields" : {
          "subid_prefix" : [
            "1"
          ]
        }
      }
    ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.