C#访问Elasticsearch(ES)

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值