背景
ES提供了restapi方便使用,这里我使用.NET客户端操作。
基本使用
.Net客户端有两个包,Elasticsearch.Net
为基础包,但是也包含了基本的操作功能,而NEST
则再次基础上封装了高级功能,我直接引用NEST
,如下
var node = new Uri("http://es.com"); var settings = new ConnectionSettings(node); settings.DefaultFieldNameInferrer(x => x.ToLower()); settings.RequestTimeout(TimeSpan.FromSeconds(3)); var client = new ElasticClient(settings); var doc = new File { Id = Guid.NewGuid(), Name = "测试文件名", Extension = ".png", Type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", FolderId = Guid.NewGuid(), Path = "/1/2" }; var response = client.Index(doc, index => index.Id(doc.Id).Index("file")); Console.WriteLine(response.IsValid);
上面代码很简单,连接并索引了一条数据,我着重说下settings.DefaultFieldNameInferrer(x => x.ToLower());
我这里设置了所有索引字段的风格为小写,因为如果大小写不同则认为是两个字段,这个大小写最好统一不然坑爹的蛋疼,因为如果你维护ES的话,不同的大小写风格实在是太容易出问题。
GET /file/_search
结果如下
{ "took" : 0, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "file_1", "_type" : "_doc", "_id" : "3f775dc8-d7f6-4799-bf75-43968c4dfbac", "_score" : 1.0, "_source" : { "id" : "3f775dc8-d7f6-4799-bf75-43968c4dfbac", "name" : "测试文件名", "extension" : ".png", "type" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "size" : 0, "path" : "/1/2", "folderid" : "c439091e-206e-4837-bec4-69bc77692efc" } } ] } }