索引(添加)
var settings = new ConnectionSettings(new Uri("http://****:9200/")).DefaultFieldNameInferrer(name => name);
var client = new ElasticClient(settings);
//index、indexDocument:添加
{
var indexResponse1 = client.IndexDocument<People>(new People { Id = 4, Age = 4, Name = new Name { Firstname = "wj", Lastname = "f" } });
var indexResponse2 = client.Index<People>(new People { Id = 4, Age = 4 }, i => i
.Index("my_index")
.Id(1)
.Routing("1")
.Refresh(Refresh.True));
var indexResponse3 = client.IndexDocument<People>(new People { Id = 4, Age = 4, Name = new Name { Firstname = "wj", Lastname = "f" } });
}
删除
//delete、deleteByQuery:删除
{
//删除指定id文档
client.Delete<ElasticUserModel>(3, d => d.Index("index13"));
//删除指定条件的文档
client.DeleteByQuery<ElasticUserModel>(d => d.Index("index13").Query(q => q.Term("UserID", 4)));
}
修改
//update:修改
{
//Update<object>只会修改指定的字段,如下只修改Name,其他字段不变。
var updateResponse = client.Update<object>(2, u => u
.Index("index13")
.Doc(new
{
Name = "fan22"
})
);
}
批量增删改
//bulk:批量增删改
{
var bulkResponse = client.Bulk(b=>b
.Update<object>(u=>u.Index("index13").Id(2).Doc(new { Name="fan222" }))
.Delete<ElasticUserModel>(d=>d.Index("index13").Id(1))
.Index<ElasticUserModel>(i=>i.Index("index13").Document(new ElasticUserModel {UserID=11,Name="fan11",Age=11,CreateTime=DateTime.Now,Handle="handle11" }))
);
}
version(乐观锁)
查询时获取文档版本号,修改时传版本号,如果相同就修改
//查询到版本号
var result = _client.Search<TestModel5>(
s =>
s.Index(indexName)
.Query(q => q.Term(tm => tm.Field(fd=>fd.State).Value(1))).Size(1)
.Version()//结果中包含版本号
);
foreach (var s in result.Hits)
{
Console.WriteLine(s.Id + " - " + s.Version);
}
var path = new DocumentPath<TestModel5>(1);
//更新时带上版本号 如果服务端版本号与传入的版本好相同才能更新成功
var response = _client.Update(path, (p) => p
.Index(indexName)
.Type(typeof(TestModel5))
.Version(2)//限制es中版本号为2时才能成功
.Doc(new TestModel5() { Name = "测测测" + DateTime.Now })
);