C#访问Elasticsearch(ES)

es 同时被 2 个专栏收录
3 篇文章 0 订阅
33 篇文章 0 订阅

C#访问Elasticsearch(ES)

前言

.net访问Elasticsearch常借助nuget包Elasticsearch.Net或Nest

Elasticsearch.Net提供了ElasticLowLevelClient来作为访问ES的客户端
而Nest提供ElasticClient来作为访问ES的客户端
二者在使用上很相似,不过光听名字也可以知道ElasticLowLevelClient比较低级,它用起来更像是在使用es原生语句,如果你对着方面不太擅长,那么你使用ElasticLowLevelClient时就会显得有些吃力。我个人的话也是比较喜欢使用ElasticClient,因为它提供了更丰富的API,可以使编码更加轻松

参考官网
使用ElasticLowLevelClient
使用ElasticClient

先讲一下ElasticLowLevelClient的基本使用

创建ES客户端,与ES服务器建立连接

如果要连接http://localhost:9200,可以简单使用

var lowlevelClient = new ElasticLowLevelClient();

如果要指定主机和端口号,可以使用

var settings = new ConnectionConfiguration(new Uri("http://localhost:9200"));
var lowlevelClient = new ElasticLowLevelClient(settings);

也可以对客户端进行一些配置

var settings = new ConnectionConfiguration(new Uri("http://localhost:9200")).RequestTimeout(TimeSpan.FromMinutes(2));
var lowlevelClient = new ElasticLowLevelClient(settings);

添加

假设要添加的数据的类型是Person

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

添加单个数据

var person = new Person
{
    FirstName = "Martijn",
    LastName = "Laarman"
};
var indexResponse = await lowlevelClient.IndexAsync<StringResponse>("people", "1", PostData.Serializable(person));
string responseString = indexResponse.Body;

添加多个数据,使用lowlevelClient.Bulk方法

var people = new object[]
{
    new { index = new { _index = "people", _type = "_doc", _id = "2"  }},
    new Person { FirstName = "Greg", LastName = "Marzouka" },
    new { index = new { _index = "people", _type = "_doc", _id = "3"  }},
    new Person { FirstName = "Russ", LastName = "Cam" }
};
var bulkResponse = await lowlevelClient.BulkAsync<StringResponse>(PostData.MultiJson(people));
string responseString = bulkResponse.Body;

查询

var searchResponse = await lowlevelClient.SearchAsync<StringResponse>("people", PostData.Serializable(new
{
    from = 0,
    size = 10,
    query = new
    {
        match = new
        {
            FirstName = new
            {
                query = "Martijn"
            }
        }
    }
}));
string responseString = searchResponse.Body;

或者使用字符串表示PostData

var searchResponse = await lowlevelClient.SearchAsync<StringResponse>("people", @"
{
    ""from"": 0,
    ""size"": 10,
    ""query"": {
        ""match"": {
            ""FirstName"": {
                ""query"": ""Martijn""
            }
        }
    }
}");

再说ElasticClient

创建ES客户端,与ES服务器建立连接

可以在创建ElasticClient客户端时指定默认的index,这样在操作数据时就不需要指定index了。嗯,这里咱们就把默认的index设为"people2"好了

如果要连接http://localhost:9200,可以简单使用

var elasticClient = new ElasticClient().DefaultIndex("people2");

如果要指定主机和端口号,可以使用

var settings = new ConnectionSettings(new Uri("http://localhost:9200")).DefaultIndex("people2");

添加

假设要添加的数据为Person2

public class Person2
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

添加单个数据

Person2 person = new Person2()
{
    Id = "1",
    FirstName = "person1",
    LastName = "person1"
};
var response = await elasticClient.IndexDocumentAsync(person);
Console.WriteLine(JsonConvert.SerializeObject(response));

添加多个数据,使用elasticClient.IndexManyAsync方法

Person2[] people = new Person2[]
{
    new Person2(){Id = "2", FirstName = "person2", LastName = "person2" },
    new Person2(){Id = "3", FirstName = "person3", LastName = "person3" }
};
var response = await elasticClient.IndexManyAsync(people);
Console.WriteLine(JsonConvert.SerializeObject(response));

个人认为,使用elasticClient.IndexManyAsync方法批量添加显然比使用lowlevelClient.BulkAsync方法更优雅

查询

var searchResponse = await elasticClient.SearchAsync<Person2>(s => s
    .Index("people2")
    .From(0)
    .Size(10)
    .Query(q => q
        .Match(m => m
            .Field(f => f.FirstName)
                .Query("person1")
            )
        )
    );
var people = searchResponse.Documents;
Console.WriteLine(JsonConvert.SerializeObject(people));

SearchRequest searchRequest = new SearchRequest("people2")
{
    From = 0,
    Size = 10,
    Query = new MatchQuery()
    {
        Field = Infer.Field<Person2>(f => f.FirstName),
        Query = "person1"
    }
};
var response = await elasticClient.SearchAsync<Person2>(searchRequest);
var people = response.Documents;
Console.WriteLine(JsonConvert.SerializeObject(people));

聚合

var searchResponse = await elasticClient.SearchAsync<Person2>(s => s
    .Aggregations(a => a
        .Terms("last_names", ta => ta
            .Field(f => f.FirstName.Suffix("keyword"))
        )
    ));
var termsAggregation = searchResponse.Aggregations.Terms("last_names");
foreach (var term in termsAggregation.Buckets)
{
    Console.WriteLine(term.Key);
    Console.WriteLine(term.DocCount);
}

降级

可以使用elasticClient.LowLevel获取到一个IElasticLowLevelClient,这个IElasticLowLevelClient使用起来就像使用ElasticLowLevelClient,并且这个IElasticLowLevelClient能够支持强类型

例如:

使用elasticClient.LowLevel得到的IElasticLowLevelClient来做查询:

var response = await elasticClient.LowLevel.SearchAsync<SearchResponse<Person2>>("people2", PostData.Serializable(new
{
    query = new
    {
        multi_match = new
        {
            fields = "firstName",
            query = "person1"
        }
    }
}));
var people = response.Documents;
Console.WriteLine(JsonConvert.SerializeObject(people));

使用elasticClient.LowLevel得到的IElasticLowLevelClient来添加数据:

Person2 person = new Person2()
{
    Id = "5",
    FirstName = "person5",
    LastName = "person5"
};
var response = await elasticClient.LowLevel.IndexAsync<StringResponse>("people2", "5", PostData.Serializable(person));
Console.WriteLine(response.Body);
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页

打赏作者

程序猿想成程序狮

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值