在ElasticSearch中,我正在尝试为文档编制索引,例如:
{
"tags": [
{
"value": "...",
"quality": 0.7
},
...
]
}
我希望它_source
包含完整的文档,但是只有那些超过某个阈值的value
s被索引quality
了。我阅读了文档,对我来说,如果我在建立索引之前以任何方式修改输入文档(例如,滤除value
s),那么修改后的文档将存储在_source
,而不是原始文档下。
有没有办法做到这一点?
有一种方法可以实现这一目标。默认情况下,该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
谢谢。这看起来很详细。有没有办法不存储
indexedTags
成_source
?您能解释一下您要对这些数据进行哪种查询吗?
您所做的查询示例几乎就是答案。我知道我可以
_source
在获取时隐藏`indexedTags`字段,但是如果不需要的话,我宁愿不必保存它(只是为了节省空间)。好的,您只需要查询
value
而从不需要quality
。是tags
类型nested
还是仅仅是类型object
?这是一个很大的问题。我确实有多个
tags
领域,其中有些是nested
但有些只是object
。因此,如果有一个可行的解决方案将是一个好主意nested
,但也只是一个object
很好的了解。