How to enforce a required field in elastic search?

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-18 04:27:06

问题


I am building a cms using elastic search on the back end and my team has decided to use elastic search. I am new to it. I mostly use mongoose with mongodb from previous projects. In mongodb if I wrong assign a field or completely skip a required field mongodb throws an error.

Is there a way to enforce required fields in elasticsearch?


回答1:


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.

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

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"
      }
    }
  ]
}

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



来源:https://stackoverflow.com/questions/42928101/how-to-enforce-a-required-field-in-elastic-search

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!