且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在弹性搜索中强制执行必填字段?

更新时间:2023-12-01 14:25:16

没有内置功能,可让您在映射中定义必填字段.许多人会建议您在客户端进行检查.

There is not built in functionality, that will allow you to define required/mandatory fields in the mappings. Many will recommend you to do checks on the client side.

但是,在Elasticsearch 5.x中,您可以通过使用Ingest节点来完成技巧.

However, in Elasticsearch 5.x you have the possibility to do the trick by using Ingest node.

您可以使用摄取节点在实际文档之前对文档进行预处理进行索引.此预处理由摄取节点进行拦截批量和索引请求,应用转换,然后将文档传递回索引API或批量API.

You can use ingest node to pre-process documents before the actual indexing takes place. This pre-processing happens by an ingest node that intercepts bulk and index requests, applies the transformations, and then passes the documents back to the index or bulk APIs.

要在索引之前对文档进行预处理,您可以定义一个管道指定一系列处理器.每个处理器都会转换文档.

To pre-process documents before indexing, you define a pipeline that specifies a series of processors. Each processor transforms the document in some way.

一个示例,显示了使用此方法的可能性.

An example, which shows the possibility of using this approach.

POST _ingest/pipeline/_simulate
{
  "pipeline": {
    "processors": [
      {
        "script": {
          "lang": "painless",
          "inline": "if (ctx.title == null) { throw new Exception('Document does not have the *title* field') }"
        }
      }
    ]
  },
  "docs": [
    {
      "_index": "index",
      "_type": "type",
      "_id": "1",
      "_source": {
        "title": "Elasticsearch 101"
      }
    },
    {
      "_index": "index",
      "_type": "type",
      "_id": "2",
      "_source": {
        "company": "Elastic"
      }
    }
  ]
}

有关更多信息,请在这里查看- https://www.elastic.co/guide/zh-CN/elasticsearch/reference/5.2/ingest.html

For more information please take a look here - https://www.elastic.co/guide/en/elasticsearch/reference/5.2/ingest.html