我有一个keyword
type'd字段,可以包含数字或字符串。如果该字段不包含任何字母,我想点击该文档。我怎样才能做到这一点?
我的索引映射如下:
{
"mappings": {
"Entry": {
"properties": {
"testField": {
"type": "keyword"
}
}
}
}
}
我的文档如下所示:
{
"testField":"123abc"
}
要么
{
"testField": "456789"
}
我试过查询:
{
"query": {
"range": {
"gte": 0,
"lte": 2000000
}
}
}
但它仍然对
123abc
命中。我该如何设计,以便仅在该特定字段中打上带有编号的文档?
最佳答案
还有另一个更理想的选择,可以精确地实现您想要的。您可以利用ingest API pipelines,并使用 script
processor可以在建立索引时创建另一个数字字段,然后可以在搜索时更有效地使用它。
下面的提取管道包含一个script
处理器,它将创建另一个名为numField
的字段,该字段仅包含数字值。
POST _ingest/pipeline/_simulate
{
"pipeline": {
"processors": [
{
"script": {
"source": """
ctx.numField = /\D/.matcher(ctx.testField).replaceAll("");
"""
}
}
]
},
"docs": [
{
"_source": {
"testField": "123"
}
},
{
"_source": {
"testField": "abc123"
}
},
{
"_source": {
"testField": "123abc"
}
},
{
"_source": {
"testField": "abc"
}
}
]
}
使用包含字母数字内容的4个不同文档来模拟此管道,将产生以下结果:
{
"docs" : [
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"numField" : "123",
"testField" : "123"
},
"_ingest" : {
"timestamp" : "2019-05-09T04:14:51.448Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"numField" : "123",
"testField" : "abc123"
},
"_ingest" : {
"timestamp" : "2019-05-09T04:14:51.448Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"numField" : "123",
"testField" : "123abc"
},
"_ingest" : {
"timestamp" : "2019-05-09T04:14:51.448Z"
}
}
},
{
"doc" : {
"_index" : "_index",
"_type" : "_type",
"_id" : "_id",
"_source" : {
"numField" : "",
"testField" : "abc"
},
"_ingest" : {
"timestamp" : "2019-05-09T04:14:51.448Z"
}
}
}
]
}
在为文档using this pipeline编制索引之后,可以对
numField
而不是testField
运行范围查询。与其他解决方案(对不起,@ Kamal)相比,它将转移脚本编制负担,使其在索引编制时每个文档仅运行一次,而不是在搜索时每次在文档上运行。{
"query": {
"range": {
"numField": {
"gte": 0,
"lte": 2000000
}
}
}
}
关于elasticsearch - 如何在Elasticsearch中查找在某个字段中包含数字的所有文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049446/