Elasticsearch .net client NEST使用说明 2.x

Elasticsearch .net client NEST使用说明 2.x

引用

Install-Package NEST

Connection链接

//单node
Var node = new Uri(“……”);
var settings = new ConnectionSettings(node);

//多node
Var nodes = new Uri [] {
       new Uri(“……”),
         new Uri(“……”)
};
//多node
Var nodes = new Node [] {
       new Node (new Uri(“……”)),
         new Node (new Uri(“……”))
};

var pool = new StaticConnectionPool(nodes);
var settings = new ConnectionSettings(pool);
var client = new ElasticClient(settings);

索引选择

方式1:

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

方式2:

var settings = new ConnectionSettings().MapDefaultTypeIndices(m => m.Add(typeof(Project), "projects")  );

方式3:

client.Search<VendorPriceInfo>(s => s.Index("test-index"));

client.Index(data,o=>o.Index("test-index"));

优先级:方式3  > 方式2  > 方式1

索引操作

创建:

client.CreateIndex("test2");

//基本配置

IIndexState indexState=new IndexState()

{
       Settings = new IndexSettings()

       {
            NumberOfReplicas = 1,//副本数

            NumberOfShards = 5//分片数
       }
};

client.CreateIndex("test2", p => p.InitializeUsing(indexState));

判断:

client.IndexExists("test2");

删除:

client.DeleteIndex("test2");

Open/Close:

client.OpenIndex("index");

client.CloseIndex("index");

添加索引数据

索引唯一Id:

1)  默认以“Id”字段值作为索引唯一Id值,无“Id”属性,Es自动生成唯一Id值,添加数据时统一类型数据唯一ID已存在相等值,将只做更新处理。

2)  标记唯一Id值

[ElasticsearchType(IdProperty = "priceID")]

    public class VendorPriceInfo
    {
        public Int64 priceID { get; set; }

        public int oldID { get; set; }

        public int source { get; set; }
}

3)  索引时指定

client.Index(data, o => o.Id(data.vendorName));

优先级: 3) > 2) > 1)

索引类型:

1)  默认类型为索引数据的类名(自动转换为全小写)

2)  标记类型

[ElasticsearchType(Name = "v3")]

    public class VendorPriceInfo
    {
        public Int64 priceID { get; set; }

        public int oldID { get; set; }

        public int source { get; set; }
    }

3)  索引时指定

client.Index(data, o => o.Type(new TypeName() { Name = "v5", Type = typeof(VendorPriceInfo) }));

client.Index(data, o => o.Type<MyClass>());

优先级:3> 2) > 1)

添加数据:

添加单条数据

var data = new VendorPriceInfo() { vendorName = "测试"};

client.Index(data);

添加多条数据

var datas = new List<VendorPriceInfo> {

                new VendorPriceInfo(){priceID = 1,vendorName = "test1"},

                new VendorPriceInfo(){priceID = 2,vendorName = "test2"}};

client.IndexMany(datas);

删除数据:

单条数据

DocumentPath<VendorPriceInfo> deletePath=new DocumentPath<VendorPriceInfo>(7);

client.Delete(deletePath);

IDeleteRequest request = new DeleteRequest("test3", "vendorpriceinfo", 0);

client.Delete(request);

集合数据

var list=new List<VendorPriceInfo> {

                new VendorPriceInfo(){priceID = 5},

                new VendorPriceInfo(){priceID = 7}};

var response = client.DeleteMany(list);

var response = client.DeleteMany(list, "test3", "vendorpriceinfo");

更新数据:

更新所有字段

DocumentPath<VendorPriceInfo> deletePath=new DocumentPath<VendorPriceInfo>(2);

Var response=client.Update(deletePath,(p)=>p.Doc(new VendorPriceInfo(){vendorName = "test2update..."}));

IUpdateRequest<VendorPriceInfo, VendorPriceInfo> request = new UpdateRequest<VendorPriceInfo, VendorPriceInfo>(deletePath)
            {
                Doc = new VendorPriceInfo()
                {
                   priceID = 888,

                    vendorName = "test4update........"
                }
            };
            var response = client.Update<VendorPriceInfo, VendorPriceInfo>(request);

更新部分字段

IUpdateRequest<VendorPriceInfo, VendorPriceInfoP> request = new UpdateRequest<VendorPriceInfo, VendorPriceInfoP>(deletePath)
            {
                Doc = new VendorPriceInfoP()
                {
                    priceID = 888,
                    vendorName = "test4update........"
                }
            };
            var response = client.Update(request);

更新部分字段

IUpdateRequest<VendorPriceInfo, object> request = new UpdateRequest<VendorPriceInfo, object>(deletePath)
            {
                Doc = new
                {
                    priceID = 888,
                    vendorName = " test4update........"
                }
            };
            var response = client.Update(request);

client.Update<VendorPriceInfo, object>(deletePath, upt => upt.Doc(new { vendorName = "ptptptptp" }));

获取数据:

获取单条

var response = client.Get(new DocumentPath<VendorPriceInfo>(0));

var response = client.Get(new DocumentPath<VendorPriceInfo>(0),pd=>pd.Index("test4").Type("v2"));

获取多条

var response = client.MultiGet(m => m.GetMany<VendorPriceInfo>(new List<long> { 1, 2, 3, 4 }));

搜索:

var result = client.Search<VendorPriceInfo>(
                 s => s
                .Explain()//返回数据的解释信息 https://www.elastic.co/guide/en/elasticsearch/reference/2.3/search-explain.html
                .FielddataFields(fs=>fs
                        .Field(p => p.vendorFullName)
                        .Field(p=>p.cbName)
                )
                //.Fields(fs => fs
                //    .Field(p => p.vendorID)
                //    .Field(p => p.cbID)
                //)
                .From(0)//跳过的数据个数
                .Size(pagesize)//返回数据个数
                .Query(q =>
                    //q.Term(p => p.vendorID, vid)
                    //&&
                    //q.Term(p => p.cbID, cbid)
                    //&&
                    q.Match(ma => ma.Field(f => f.vendorName).Query("测试"))
                    //q.Bool(b => b.Must(m => m.Term(p => p.vendorID, vid) && m.Term(p=>p.cbID,cbid)))
                    )//查询条件
                .Sort(st => st.Ascending(asc => asc.vendorPrice))//排序
               );

var result = client.Search<VendorPriceInfo>(new SearchRequest()
        {
            Sort =new List<ISort>
                   {
                        new SortField { Field = "vendorPrice", Order = SortOrder.Ascending }
                    },
            Size = 10,
            From = 0,
            Query = new TermQuery()
            {
                Field = "priceID",
                Value = 6
            }
            ||
            new TermQuery()
            {
                Field = "priceID",
                Value = 8
            }
        });
时间: 2024-08-29 12:13:03

Elasticsearch .net client NEST使用说明 2.x的相关文章

(转)Elasticsearch .net client NEST使用说明 2.x

Elasticsearch.Net与NEST是Elasticsearch为C#提供的一套客户端驱动,方便C#调用Elasticsearch服务接口.Elasticsearch.Net是较基层的对Elasticsearch服务接口请求响应的实现,NEST是在前者基础之上进行的封装.本文是针对NEST的使用的总结. 引用 Install-Package NEST 包含以下dll NEST.dll Elasticsearch.Net.dll   Newtonsoft.Json.dll 概念 存储结构:

ElasticSearch 之 Client

在使用ElasticSearch的时候,我们需要与Cluster通信,Java版本的API提供了几种方式来构造Client,进而通过Client操作Cluster. 1)使用Node与clustor通信 原理:通过在程序中创建一个嵌入es节点(Node),使之成为ElasticSearch集群的一部分,然后通过这个节点来与ElasticSearch集群通信. 最简单的方式: Node node = NodeBuilder.nodeBuilder().node(); Client client =

elasticsearch系列七:ES Java客户端-Elasticsearch Java client(ES Client 简介、Java REST Client、Java Client、Spring Data Elasticsearch)

一.ES Client 简介 1. ES是一个服务,采用C/S结构 2. 回顾 ES的架构 3. ES支持的客户端连接方式 3.1 REST API ,端口 9200 这种连接方式对应于架构图中的RESTful style API这一层,这种客户端的连接方式是RESTful风格的,使用http的方式进行连接 3.2 Transport 连接 端口 9300 这种连接方式对应于架构图中的Transport这一层,这种客户端连接方式是直接连接ES的节点,使用TCP的方式进行连接 4. ES提供了多种

Elasticsearch(八)【NEST高级客户端--Mapping映射】

要使用NEST与Elasticsearch进行交互,我们需要能够将我们的解决方案中的POCO类型映射到存储在Elasticsearch中的反向索引中的JSON文档和字段.本节介绍NEST中可用的所有不同功能,使POCO和Elasticsearch变得轻而易举. 在Elasticsearch中显式映射文档对于为给定的问题域提供定制搜索解决方案至关重要.虽然Elasticsearch能够基于遇到的该类型的第一个文档来推断索引中给定类型的映射,但推测的映射有时不足以构建一个非常优秀的搜索体验. 要显式

Elasticsearch之client源码简要分析

问题 让我们带着问题去学习,效率会更高 1  es集群只配置一个节点,client是否能够自动发现集群中的所有节点?是如何发现的? 2  es client如何做到负载均衡? 3  一个es node挂掉之后,es client如何摘掉该节点? 4  es client node检测分为两种模式(SimpleNodeSampler和SniffNodesSampler),有什么不同? 核心类 TransportClient    es client对外API类 TransportClientNod

写个Elasticsearch的client库简化操作

[TestMethod] public void Analyze() { string[] d = mIndex.Analyze("c# socket", "ik"); } [TestMethod] public void match() { IList<Blog> items = mIndex.Query<Blog>(q => q.Match(new SearchMatch { field = "title", q

【ElasticSearch+NetCore 第二篇】Nest封装

using Elasticsearch.Net; using Nest; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ESStudy.Website { public static class EsUtil { /// <summary> /// 获取ElasticClient /// </summary> //

Elasticsearch.net&amp;Nest 的使用

static void Main(string[] args) { Nest(); Console.WriteLine("End.."); Console.ReadKey(); //MyUser user = new MyUser(); //var indexResponse = lowlevelClient.Index<byte[]>("user", "guest", user.name, user); //byte[] respo

Elastcisearch.Nest 7.x 系列`伪`官方翻译:通过 NEST 来快捷试用 Elasticsearch

本系列已经全部完成,完整版可见 :https://blog.zhuliang.ltd/categories/Elasticsearch/ 本系列博文是"伪"官方文档翻译(更加本土化),并非完全将官方文档进行翻译,而是在查阅.测试原始文档并转换为自己真知灼见后的"准"翻译.有不同见解 / 说明不周的地方,还请海涵.不吝拍砖 :) 官方文档见此:https://www.elastic.co/guide/en/elasticsearch/client/net-api/cu