gpt4 book ai didi

c# - 带有版本控制的Elasticsearch更新-NEST/C#

转载 作者:行者123 更新时间:2023-12-02 23:25:31 25 4
gpt4 key购买 nike

我希望实现 flex 搜索版本控制功能,以使用NEST库和C#更新记录。我实际上正在寻找创建执行以下操作的助手:

  • 读取现有记录。
  • 更改记录。
  • 使用版本功能更新文档。

  • 我已经完成了一些研究,但没有找到所需的信息。谁能给我指出一些代码示例,实现或测试?

    最佳答案

    我使用以下类,其中包括版本化Update

    public class SampleElasticClient
    {
    private const string VERSION_CONFLICT_ERROR = "version_conflict_engine_exception";

    protected readonly string IndexName;

    protected readonly ElasticClient Client;

    public SampleElasticClient(Uri uri, string indexName)
    {
    Client = new ElasticClient(new ConnectionSettings(uri).DefaultIndex(indexName));
    IndexName = indexName;
    }

    public IGetResponse<T> Get<T>(Id id) where T : class
    {
    var request = new GetRequest<T>(IndexName, typeof(T), id);
    var response = Client.Get<T>(request);
    EnsureSuccessResponse(response);
    return response;
    }

    public void Update<T>(Id id, Func<T, T> update, int retriesCount = 10) where T : class
    {
    Retry(() =>
    {
    var getResponse = Get<T>(id);
    var item = update(getResponse.Source);
    return Client.Index(item, index => getResponse.Found
    ? index.Version(getResponse.Version)
    : index.OpType(OpType.Create));
    }, retriesCount);
    }

    protected void EnsureSuccessResponse(IResponse response)
    {
    if (!response.IsValid && response.ApiCall.HttpStatusCode != 404)
    {
    var errorMessage = response.ServerError != null
    ? $"ElasticSearch error: {response.ServerError.Error}\r\n" +
    $"Http status: {response.ServerError.Status}"
    : $"ElasticSearch error. {response.DebugInformation}";
    throw new Exception(errorMessage);
    }
    }

    protected void Retry(Func<IResponse> execute, int retriesCount)
    {
    var numberOfRetry = 0;
    do
    {
    var response = execute();
    if (response.ServerError?.Error.Type != VERSION_CONFLICT_ERROR || ++numberOfRetry == retriesCount)
    {
    EnsureSuccessResponse(response);
    return;
    }
    } while (true);
    }
    }

    负责处理 Retry和重试更新的 version_conflict_engine_exception方法。 Update方法通过使用lambda来处理从索引中检索到的实体,从而插入或更新实体。这是使用此类的示例
    var client = new SampleElasticClient(new Uri("http://localhost:9200"), indexName);
    var id = 123;
    client.Update<Sample>(id, entity =>
    {
    if (entity == null)
    entity = new Sample { Id = id }; // Or any other action for new entity

    entity.MyField = "new value";
    return entity;
    });

    关于c# - 带有版本控制的Elasticsearch更新-NEST/C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43814900/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com