Warm tip: This article is reproduced from serverfault.com, please click

elasticsearch-跳过数组中某些值的索引编制,但将其保留在_source中

(elasticsearch - Skipping indexing of some values in an array, but keeping them in _source)

发布于 2020-11-26 05:44:14

在ElasticSearch中,我正在尝试为文档编制索引,例如:

{
  "tags": [
    {
       "value": "...",
       "quality": 0.7
    },
    ...
  ]
}

我希望它_source包含完整的文档,但是只有那些超过某个阈值的values被索引quality了。我阅读了文档,对我来说,如果我在建立索引之前以任何方式修改输入文档(例如,滤除values),那么修改后的文档将存储在_source,而不是原始文档下

有没有办法做到这一点?

Questioner
Mitar
Viewed
11
5,711 2020-11-30 15:02:00

有一种方法可以实现这一目标。默认情况下,该tags结构在映射中处于禁用状态(即未建立索引)。然后,通过利用摄取处理器,你可以创建一个二级tags结构(我称之为indexedTags),该二级结构将仅包含其quality组成部分高于给定阈值的标记元素

因此,映射应如下所示:

PUT test 
{
  "mappings": {
    "properties": {
      "tags": {
        "enabled": false,        <--- won't be indexed at all, but still present in _source
        "properties": {
          "value": {
            "type": "text"
          },
          "quality": {
            "type": "float"
          }
        }
      },
      "indexedTags": {           <--- will only contain indexable values above threshold
        "properties": {
          "value": {
            "type": "text"
          },
          "quality": {
            "type": "float"
          }
        }
      }
    }
  }
}

然后,我们需要创建一个摄取管道,以允许我们过滤正确的标签值。以下摄取处理器使用脚本处理器来创建一个indexedTags数组tags,并且数组将仅包含其quality字段大于定义的阈值(例如,在本例中为0.6)的元素

PUT _ingest/pipeline/quality-threshold
{
  "processors": [
    {
      "script": {
        "source": """
          ctx.indexedTags = ctx.tags.stream().filter(t -> t.quality > params.threshold).collect(Collectors.toList());
        """,
        "params": {
          "threshold": 0.6
        }
      }
    }
  ]
}

最后,我们可以在索引文档时利用该摄取管道:

PUT test/_doc/1?pipeline=quality-threshold
{
  "tags": [
    {
      "value": "test",
      "quality": 0.5
    },
    {
      "value": "test2",
      "quality": 0.8
    }
  ]
}

运行上述命令时,整个tags数组仍将存在于中,_source但不会被索引。但是,将索引的是另一个调用的数组,该数组indexedTags将仅包含第二个元素(即test2),因为它的quality值为0.8且高于0.6阈值。

该文档如下所示:

  {
    "_index" : "test",
    "_type" : "_doc",
    "_id" : "1",
    "_score" : 0.2876821,
    "_source" : {
      "indexedTags" : [
        {
          "value" : "test2",
          "quality" : 0.8
        }
      ],
      "tags" : [
        {
          "value" : "test",
          "quality" : 0.5
        },
        {
          "value" : "test2",
          "quality" : 0.8
        }
      ]
    }
  }

现在,test通过搜索,你可以看到根本没有索引第一个元素

GET test/_search?q=test
=> No results

搜索时test2将检索你的文档:

GET test/_search?q=test2
=> Returns document 1