Usando o Elasticsearch.Net como Cliente do Elasticsearch

var node = new Uri("http://myserver:9200");
var config = new ConnectionConfiguration(node);
var client = new ElasticLowLevelClient(config);

var meuJson = @"{ ""hello"" : ""world"" }";
client.Index<StringResponse>("myindex", "1", meuJson);
var meuJson = new { hello = "world" };
client.Index<BytesResponse>("myindex", "1", PostData.Serializable(meuJson));

Encapsulamento do Elasticsearch.Net

  • Crie a classse ClienteElasticsearch
public class ClienteElasticsearch
{
    public ElasticLowLevelClient Client { get; }

    private readonly IConfiguration _configuracao;

    public ClienteElasticsearch(IConfiguration configuracao)
    {
        _configuracao = configuracao;
        Client = InicializarCliente();
    }

    #region Métodos
    public async Task<string> Indexar(string indice, string id, PostData corpo)
    {
        var resposta = await Client.IndexAsync<StringResponse>(indice, id, corpo);
        ValidarResposta(resposta);
        return resposta.Body;
    }

    public async Task<List<string>> PesquisarComDestaque(string indice, string consulta)
    {
        var resposta = await Client.SearchAsync<StringResponse>(
            indice,
            PostData.Serializable(new
            {
                from = 0,
                size = 100,
                query = new
                {
                    match = new
                    {
                        conteudo = consulta
                    }
                },
                highlight = new
                {
                    pre_tags = new[] { "<tag1>", "<tag2>" },
                    post_tags = new[] { "/<tag1>", "/<tag2>" },
                    fields = new
                    {
                        conteudo = new { }
                    }
                }
            }));

        ValidarResposta(resposta);
        var respostaJson = (JObject)JsonConvert.DeserializeObject(resposta.Body);

        var hits = respostaJson["hits"]["hits"] as JArray;

        var resultados = new List<string>();

        foreach (var hit in hits)
        {
            var id = hit["_id"].ToObject<string>();
            resultados.Add(id);
        }

        return resultados;
    }

    public async Task Deletar(string indice, string id)
    {
        var resposta = await Client.DeleteAsync<StringResponse>(indice, id);
        ValidarResposta(resposta);
    }
    #endregion

    #region Privados
    private ElasticLowLevelClient InicializarCliente()
    {
        var node = new Uri(_configuracao.GetConnectionString("ElasticSearch"));
        var configuracoes = new ConnectionConfiguration(node);
        return new ElasticLowLevelClient(configuracoes);
    }

    private void ValidarResposta(StringResponse resposta)
    {
        if (resposta.Success == false)
        {
            throw new ExcecaoResultado(resposta.Body);
        }
    }
    #endregion
}

  • Injeção de dependência em Startup.cs: services.AddScoped<ClienteElasticsearch>();
  • Utilização
private readonly ClienteElasticsearch _clienteElasticsearch;
await _clienteElasticsearch.Indexar(Artigo.IndiceEs, artigo.ArticleUID, PostData.Serializable(artigo));

Tags: elasticsearch Elasticsearch.Net C# ASP.NET Core cliente http

Publicado em 7-27 21:47