C# ElasticSearch 简单使用方法

2022年12月29日 1777点热度 0人点赞 0条评论
内容纲要

连接

如果不想对外暴露密码,可以自行写一个 AuthorizationHeader,只使用 Base64 处理后的 Basic 认证密钥。

using Elastic.Clients.Elasticsearch;
using Elastic.Transport;

public class Program
{
    public class Base64Auth : AuthorizationHeader
    {
        private readonly string _base;
        public Base64Auth(string baseStr)
        {
            _base = baseStr;
        }
        public override string AuthScheme => "Basic";

        public override bool TryGetAuthorizationParameters(out string value)
        {
            value = _base;
            return true;
        }
    }
    static async Task Main()
    {
        var settings = new ElasticsearchClientSettings(new Uri("http://192.168.111.111:9200"))
            .Authentication(new Base64Auth("1111111111="))
            // 连接成功后执行
            .OnRequestCompleted(handler =>
            {

            });
        var client = new ElasticsearchClient(settings);

    }
}

或者使用账号密码。

            .Authentication(new BasicAuthentication("elastic", "12345"));

账号密码转 Base64 的方法:

Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))

插入文档

向指定的索引插入一份文档,如果索引不存在,则会自动创建。

... ...
        var client = new ElasticsearchClient(settings);
        var tweet = new Tweet
        {
            Id = 1,
            User = "stevejgordon",
            PostDate = new DateTime(2009, 11, 15),
            Message = "Trying out the client, so far so good?"
        };

        var response = await client.IndexAsync(tweet, request => request.Index("my-tweet-index"));
        if (response.IsValidResponse)
        {
            Console.WriteLine($"Index document with ID {response.Id} succeeded.");
        }
    }
    public class Tweet
    {
        public int Id { get; set; }
        public string User { get; set; }
        public DateTime PostDate { get; set; }
        public string Message { get; set; }
    }

获取文档

获取刚刚插入的文档:

        var response = await client.GetAsync<Tweet>(1, idx => idx.Index("my-tweet-index"));
        var tweet = response.Source;

file

使用 Lambda 搜索文档以及分页:

        var client = new ElasticsearchClient(settings);
        var response = await client.SearchAsync<Tweet>(s => s
            .Index("my-tweet-index")
            .From(0)
            .Size(10)
            .Query(q => q
                .Term(t => t.User, "stevejgordon")
            )
        );

        if (response.IsValidResponse)
        {
            var tweet = response.Documents.FirstOrDefault();
        }

或使用 Json 格式的搜索方法:

        var client = new ElasticsearchClient(settings);
        var request = new SearchRequest("my-tweet-index")
        {
            From = 0,
            Size = 10,
            Query = new TermQuery("user") { Value = "stevejgordon" }
        };

        var response = await client.SearchAsync<Tweet>(request);

        if (response.IsValidResponse)
        {
            var tweet = response.Documents.FirstOrDefault();
        }

更新

更新指定 Id 条件的文档:

        Tweet tweet = new Tweet
        {
            Id = 1,
            User = "stevejgordon",
            PostDate = new DateTime(2009, 11, 15),
            Message = "Trying out the client, so far so good?"
        };
        tweet.Message = "This is a new message";

        var response = await client.UpdateAsync<Tweet, object>("my-tweet-index", 1, u => u
                .Doc(tweet));

        if (response.IsValidResponse)
        {
            Console.WriteLine("Update document succeeded.");
        }

删除文档

        var response = await client.DeleteAsync("my-tweet-index", 1);

        if (response.IsValidResponse)
        {
            Console.WriteLine("Delete document succeeded.");
        }

痴者工良

高级程序员劝退师

文章评论