Simple Usage of C# with ElasticSearch

2022年12月29日 90点热度 0人点赞 0条评论
内容目录

Connection

If you don't want to expose the password, you can create your own AuthorizationHeader and use only the Base64 encoded Basic authentication key.

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="))
            // Execute after successful connection
            .OnRequestCompleted(handler =>
            {

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

Or use username and password.

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

Method to convert username and password to Base64:

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

Inserting Documents

Insert a document into a specified index. If the index does not exist, it will be created automatically.

... ...
        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; }
    }

Retrieving Documents

Retrieve the document that was just inserted:

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

file

Use Lambda to search for documents and paginate:

        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();
        }

Or use the JSON format for the search method:

        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();
        }

Updating

Update a document with the specified 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.");
        }

Deleting Documents

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

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

痴者工良

高级程序员劝退师

文章评论