Elasticsearch-C#操作
阅读原文时间:2023年07月11日阅读:1

初始化实例

nuget安装

1、单点连接

var node = new Uri("http://myserver:9200");
var settings = new ConnectionSettings(node);
var client = new ElasticClient(settings);

2、连接池连接

var nodes = new Uri[]
{
new Uri("http://myserver1:9200"),
new Uri("http://myserver2:9200"),
new Uri("http://myserver3:9200")
};
var pool = new StaticConnectionPool(nodes);
var settings = new ConnectionSettings(pool);
var client = new ElasticClient(settings);

3、指定索引

可以通过ConnectionSettings使用.DefaultIndex(),来指定默认索引。当一个请求里没有指定具体索引时,NEST将请求默认索引。

var settings = new ConnectionSettings()
.DefaultIndex("defaultindex");

新增

var nodes = new Uri[]
{
new Uri("http://localhost:9200")
};
var pool = new StaticConnectionPool(nodes);
var settings = new ConnectionSettings(pool).DefaultIndex("crm.base.log").BasicAuthentication("elastic", "caKBawShu0Pm7BsjSFbd");
var client = new ElasticClient(settings);
var log = new CreateRequest(Guid.NewGuid());
log.Document = new CRMLog();
log.Document.LogLevel = ;
log.Document.HttpMethod = "Get";
client.Create(log);

删除

根据ID删除

client.Delete(new DocumentPath("aca1f759-43ec-4c2c-b9ce-fe0f6c644a48"));

client.Delete(new DeleteRequest("crm.base.log", "4bd0ffb9-f5fc-4748-94f6-b41c706cc4ca"));

删除多条

var bulkDel = new BulkRequest() { Operations = new List() };
bulkDel.Operations.Add(new BulkDeleteOperation("4bd0ffb9-f5fc-4748-94f6-b41c706cc4ca"));
bulkDel.Operations.Add(new BulkDeleteOperation("aca1f759-43ec-4c2c-b9ce-fe0f6c644a48"));
var resultDel = client.Bulk(bulkDel);

从新指定索引

client.Delete("", s => s.Index(""));

修改

IUpdateRequest request = new UpdateRequest("6cfb5050-d175-4fb1-8f8d-c6d88cb0e2a4")
{
Doc = new CRMLog()
{
LogLevel = ,
HttpMethod = "test4update…….."
}
};
var resp = client.Update(request);

更新多条

var bulkUpdate = new BulkRequest() { Operations = new List() };
bulkUpdate.Operations.Add(new BulkUpdateOperation("6cfb5050-d175-4fb1-8f8d-c6d88cb0e2a4") { Doc = new CRMLog() { HttpMethod = "xiugai" } });
bulkUpdate.Operations.Add(new BulkUpdateOperation("aca1f759-43ec-4c2c-b9ce-fe0f6c644a48") { Doc = new CRMLog() { HttpMethod = "xiugai1" } });
var result = client.Bulk(bulkUpdate);

查询

var modUser = client.Get("6cfb5050-d175-4fb1-8f8d-c6d88cb0e2a4");
var tweet = JsonConvert.SerializeObject(modUser.Source);

多查询

var modList = client.Search(s => s
.From()
.Size()
.Query(q =>
q.Term(t => t.HttpMethod, "www.b.com")
|| q.Match(mq => mq.Field(f => f.HttpMethod).Query("Get"))
)
);

重新指定索引

client.Search(s => s.Index("crm.base.log"));

代码下载

推荐链接

https://blog.csdn.net/manimanihome/article/details/55682494

https://www.cnblogs.com/zhy-1992/p/7244440.html

https://www.jianshu.com/p/f178e59ffaf2

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章