首页 > 解决方案 > 弹性搜索:将值限制为枚举列表

问题描述

寻找一种将 ElasticSearch 的索引映射中的字段限制为已知单词列表的方法。

/myIndex
{ "mapping": {
  "demo1": { 
    "type": "keyword", 
    "allowed_values": [ "a", "b", "c" ] 
   }
}

好像没有type: enum可用的字段。有谁知道如何实现这一目标?

标签: elasticsearch

解决方案


弹性搜索是无模式的。它允许任意数量的字段和字段中的任何内容,而没有任何逻辑约束。

在分布式系统中,完整性检查可能很昂贵,因此像 RDBMS 这样的检查在弹性搜索中不可用。

最好的方法是在客户端进行验证。

另一种方法是使用摄取

摄取管道可让您在索引之前对数据执行常见转换。例如,您可以使用管道删除字段、从文本中提取值并丰富您的数据。

For testing
POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "script": {
          "lang": "painless",
          "source": "if (ctx.demo1 !='a' && ctx.demo1 !='b' && ctx.demo1 !='c') { throw new Exception('Add valid values') }"
        }
      }
    ]
  },
  "docs": [
    {
      "_index": "index",
      "_id": "1",
      "_source": {
        "demo1": "a"
      }
    },
    {
      "_index": "index",
      "_id": "2",
      "_source": {
        "demo1": "d"
      }
    }
  ]
}

Ingest pipeline

PUT _ingest/pipeline/check-value_pipeline
{
  "description": "Check if demo field has valid values",
  "processors": [
    {
      "script": {
        "lang": "painless",
        "source": "if (ctx.demo1 !='a' && ctx.demo1 !='b' && ctx.demo1 !='c') { throw new Exception('Add valid values') }"
      }
    }
  ]
}

This will throw error
POST index115/_doc?pipeline=check-value_pipeline
{
  "demo1":"d"
}


推荐阅读