Nest客户端的基本使用方法

时间:2023-03-08 17:49:42
Nest客户端的基本使用方法

通过Nuget安装好Nest的相关Dll,之后我们就可以开始了,

1.初始化Nest客户端

string indexName = "customer";
Uri uri = new Uri("http://localhost:9200");
ConnectionSettings settings = new ConnectionSettings(uri);
settings.DisableDirectStreaming().DefaultIndex(indexName);
ElasticClient client = new ElasticClient(settings);

2.创建一个Customer索引

    dynamic response = client.GetIndex(indexName);
if(!response.IsValid)
{
response = client.CreateIndex("customer");
Console.WriteLine(response);
}

3.创建文档

   var company = new Company { CompanyID=2, Name="IBM" };
//创建文档并指定索引,和文档ID
response = client.Index(company, i => i.Index(indexName).Id(company.CompanyID));
//创建文档并指定索引,文档类型,未指定文档ID,ElasticSearch会帮你生成一个随机的ID
response = client.Index(company, i => i.Index(indexName));
//这里没有显示指定索引,所以使用的客户端初始化默认索引,如果没有默认索引,就会发生错误
response = client.Index(company);

4.修改文档1

根据CompanyID来修改文档,如果存储里存在一个CompanyID等于2的文档,他就会用新的替换旧的,否则就创建一个。

所以叫创建式修改比较合适

 company = new Company { CompanyID = 2, Name = "联想" };
//修改文档
response = client.Index(company, i => i.Id(company.CompanyID));

5.修改指定版本号的文档(对乐观锁的实现)

  company = new Company { CompanyID = 2, Name = "联想" };
//修改指定版本的文档
response = client.Index(company, i => i.Id(company.CompanyID).Version(1));

6.删除文档

//根据特定的条件来删除文档
response = client.Delete<Company>(company.CompanyID, d => d.Index(indexName));
//删除文档
response = client.Delete<Company>(company.CompanyID);

7.删除索引

    //根据名称删除索引
response=client.DeleteIndex(indexName);

8.批量创建文档

这里是指定了相应的索引,如果没有显示指定索引,都是用的默认索引,

//批量创建文档
BulkDescriptor descriptor = new BulkDescriptor();
descriptor.Index<Company>(op => op.Document(new Company { CompanyID = 1, Name = "IBM" }).Index("a"));
descriptor.Index<Company>(op => op.Document(new Company { CompanyID = 2, Name = "IBM" }).Index("b"));
descriptor.Index<Company>(op => op.Document(new Company { CompanyID = 3, Name = "IBM" }).Index("c")); response = client.Bulk(descriptor);