如何避免使用 Nest .NET 6.x 将重复项发布到 elasticsearch?

How to avoid posting duplicates into elasticsearch using Nest .NET 6.x?

当来自设备的数据进入弹性时,就会有重复项。我想避免重复。我正在使用 IElasticClient、.NET 和 NEST 的对象来放置数据。

我搜索了类似ElasticClient.SetDocumentId()的方法,但找不到。

_doc doc = (_doc)obj;
HashObject hashObject = new HashObject { DataRecordId = doc.DataRecordId, TimeStamp = doc.Timestamp };
// hashId should be the document ID.
int hashId = hashObject.GetHashCode();
ElasticClient.IndexDocumentAsync(doc);

我想更新 Elastic 中的数据集而不是现在再添加一个相同的对象。

假设如下设置

var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(pool)
    .DefaultIndex("example")
    .DefaultTypeName("_doc");

var client = new ElasticClient(settings);

public class HashObject
{
    public int DataRecordId { get; set; }
    public DateTime TimeStamp { get; set; }
}

如果要在请求中明确设置文档的 Id,可以使用

语法流畅

var indexResponse = client.Index(new HashObject(), i => i.Id("your_id"));

对象初始化语法

var indexRequest = new IndexRequest<HashObject>(new HashObject(), id: "your_id");   
var indexResponse = client.Index(indexRequest);

两者都会产生一个请求

PUT http://localhost:9200/example/_doc/your_id
{
  "dataRecordId": 0,
  "timeStamp": "0001-01-01T00:00:00"
}

正如 Rob 在问题评论中指出的那样,NEST 有一个约定,通过在名为 Id 的 CLR POCO 上查找 属性,它可以从文档本身推断出 Id。如果它找到一个,它将使用它作为文档的 Id。这确实意味着 Id 值最终存储在 _source 中(并被索引,但您可以在映射中禁用它),但它很有用,因为 Id 值自动与文档关联并在需要时使用。

如果 HashObject 更新为具有 Id 值,现在我们可以做

语法流畅

var indexResponse = client.IndexDocument(new HashObject { Id = 1 });

对象初始化语法

var indexRequest = new IndexRequest<HashObject>(new HashObject { Id = 1});  
var indexResponse = client.Index(indexRequest);

哪个将发送请求

PUT http://localhost:9200/example/_doc/1
{
  "id": 1,
  "dataRecordId": 0,
  "timeStamp": "0001-01-01T00:00:00"
}

如果您的文档在 _source 中没有 id 字段,您需要自己处理每个命中的命中元数据中的 _id 值。例如

var searchResponse = client.Search<HashObject>(s => s
    .MatchAll()
);

foreach (var hit in searchResponse.Hits)
{
    var id = hit.Id;
    var document = hit.Source;

    // do something with them
}

非常感谢 Russ 提供的详细且易于理解的描述! :-)

HashObject 应该只是一个帮手,可以从我的真实 _doc 对象中获取唯一 ID。现在,我将一个 Id 属性 添加到我的 _doc class 中,其余的我将在下面的代码中显示。我现在在 Elastic 中得到了更多的副本。

public void Create(object obj)
{
    _doc doc = (_doc)obj;
    string idAsString = doc.DataRecordId.ToString() + doc.Timestamp.ToString();
    int hashId = idAsString.GetHashCode();
    doc.Id = hashId;
    ElasticClient.IndexDocumentAsync(doc);
}