elasticsearch 如何在批量插入时为Elastic Search中的`_id`属性添加自定义客户端生成的UUID

mutmk8jj  于 5个月前  发布在  ElasticSearch
关注(0)|答案(1)|浏览(66)

我正在使用Elasticsearch docker镜像版本:* docker.elastic.co/elasticsearch/elasticsearch:7.16.2*
为了让ElasticSearch在_id字段上接受客户端自定义的UUID,我必须将:"dynamic": "strict"属性更改为true
一直以来,我们都在为_id字段使用严格和自动生成的UUID。
在检查新插入的文档时,我注意到添加了一个新字段:id,其内容与_id元数据字段完全匹配。
这是预期的行为吗?这是实现我开始做的事情的正确方法吗?这是生成UUID,客户端,然后通过批量插入方法推到ELASTIC。
我在dotnet 7中使用c#和nest nuget包。
谢谢你的阅读。

通过 Postman

当我尝试通过 Postman 插入单个文档时:
x1c 0d1x的数据
你可以看到,客户端生成的UUID被分配给_id字段。Elastic只是忽略该值并自动生成一个新的。

Dto/Model Code

public interface IElasticDocumentId
{
    string id { get; set; }
}

public class SurfaceScanDocument : IElasticDocumentId
{
    public SurfaceScanDocument()
    {
        fs = new Fs();
    }
    public Fs fs { get; set; }

    public string id { get; set; }
    public string file_name { get; set; }
    public object file_type { get; set; }
    public DateTime? ingest { get; set; }
}

字符串

插入嵌套代码:

public async Task InsertDocumentWithId<T>(string indexName, T document) where T : class, IElasticDocumentId
    {
        try
        {
            var client = _elasticSearchClientProvider.GetElasticClient();
            var indexResponse = await client.IndexAsync(document, i => i
                .Index(indexName)
                .Id(document.id)
                .Refresh(Refresh.True));

            if (!indexResponse.IsValid)
            {
                throw new Exception($"Error to insert document: {indexResponse.DebugInformation}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred: {ex.Message}");
            throw;
        }
    }

h7wcgrx3

h7wcgrx31#

TDLR;

不,这不是预期的行为。_id是元数据字段,它不应该是Map的一部分。
所以你不应该设置dynamic: true

解决方案

要在设置_id时接收文档,您应该执行以下操作:

POST 77646387/_doc/1
{
  "some": "data"
}

字符串
当你搜索这份文件时,你会发现

{
  "took": 0,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "77646387",
        "_id": "1",
        "_score": 1,
        "_source": {
          "some": "data"
        }
      }
    ]
  }
}


对于批量API,它非常接近:

POST _bulk
{"create": {"_index": "77646387", "_id": 2}}
{"some": "more data"}


我不知道.net lib是什么。

相关问题