ElasticSearch.net NEST批量创建修改删除索引完整示例
本示例采用Elasticsearch+Nest
网上查了很多资料,发现用C#调用Elasticsearch搜索引擎的功能代码很分散,功能不完整,多半是非常简单的操作,没有成型的应用示例。比如新增或修改索引,都是发起一个request新增或修改一条数据,当一次性修改几千条数据时,发起的requst请求过多容易导致429 Too Many Request的错误,单个新增修改索引就非常不适用。其实Nest有批量新增、修改索引的功能,批量删除也可以。现将项目中采用Elasticsearch的C#代码分享如下:
使用NEST客户端
1.连接
- public ElasticClient GetElasticClient(string esServer, string IndexName)
- {
- ElasticClient client = null;
- string[] server = esServer.Split(',');
- Uri[] nodes = new Uri[server.Length];
- for (int i = 0; i < server.Length;i++ )
- {
- nodes[i] = new Uri(server[i]);
- }
- var connectionPool = new StaticConnectionPool(nodes);
- var settings = new ConnectionSettings(
- connectionPool
- );
- settings.DefaultIndex(IndexName);
- client = new ElasticClient(settings);
- return client;
- }
2.添加索引
- var indexExist = client.IndexExists(IndexName);
- if (!indexExist.Exists)
- {
- //基本配置
- IIndexState indexState = new IndexState()
- {
- Settings = new IndexSettings()
- {
- NumberOfReplicas = 1,//副本数
- NumberOfShards = 6//分片数
- }
- };
- //ICreateIndexResponse response = client.CreateIndex(IndexName, p => p.Mappings(m => m.Map<ES_PUB_Stock>(mp => mp.AutoMap())));
- ICreateIndexResponse response = client.CreateIndex(IndexName, p => p
- .InitializeUsing(indexState)
- .Mappings(ms =>
- ms.Map<ES_PUB_Stock>(m =>
- m.AutoMap()
- .Properties(ps =>
- ps.Nested<ES_PUB_StockPrice>(n =>
- n.Name(c => c.stockPrice)
- )
- .Nested<ES_PUB_SpecValue>(q=>
- q.Name(c=>c.specValue))))));
- if (response.IsValid)
- {
- string msg = string.Format("索引创建" + IncrementIndexName + "成功!");
- this.WriteLog(msg);
- }
- else
- {
- string msg = string.Format("索引创建" + IncrementIndexName + "失败!");
- this.WriteLog(msg);
- Thread.CurrentThread.Abort();
- }
- }
这里创建索引设置6个分片数,并Mapping自定义的结构。
Mapping相关类型如下:
- <span style="font-size:14px;">using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Nest;
- namespace SearchMaker.Model.ES.PUB
- {
- [ElasticsearchType(IdProperty = "sid", Name = "ES_PUB_Stock")]
- public class ES_PUB_Stock
- {
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public long? sid { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string model { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string brand { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string encapsulation { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string batchNo { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int invQty { get; set; }
- [Date(Format = "yyyy-MM-dd HH:mm:ss")]
- public string updateTime { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int upByMemberID { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string upByMemberName { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string guid { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public decimal? price { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int? leastQty { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int limitTime { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string proImg { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string categoryNO { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string proRemark { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int type { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int sendToday { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int pickedToday { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string categoryName { get; set; }
- [Object(Path = "specValue")]
- public List<ES_PUB_SpecValue> specValue { get; set; }
- [Object(Path = "stockPrice")]
- public List<ES_PUB_StockPrice> stockPrice { get; set; }
- [String(Analyzer = "ik", Index = FieldIndexOption.Analyzed)]
- public string specsName { get; set; }
- [String(Analyzer = "ik", Index = FieldIndexOption.Analyzed)]
- public string keyword { get; set; }
- [String(Analyzer = "ik", Index = FieldIndexOption.Analyzed)]
- public string modelAS { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int modelLength { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public decimal score { get; set; }
- }
- [ElasticsearchType(Name = "ES_PUB_StockPrice")]
- public class ES_PUB_StockPrice
- {
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public int? minval { get; set; }
- [Number(Index = NonStringIndexOption.NotAnalyzed, DocValues = false, IgnoreMalformed = true, Coerce = true)]
- public decimal? price { get; set; }
- }
- [ElasticsearchType(Name = "ES_PUB_Specs")]
- public class ES_PUB_SpecValue
- {
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string spec { get; set; }
- [String(Index = FieldIndexOption.NotAnalyzed)]
- public string value { get; set; }
- }
- }
- </span>
这里中文分词采用IK分词
3.单个新增、修改索引
- <span style="font-size:14px;"> private int CreateIndex(ES_PUB_Stock param)
- {
- int indexCnt = 0;
- if (param.sid.GetValueOrDefault(0) > 0)
- {
- var response = client.Index<ES_PUB_Stock>(param, i => i.Index(IndexName).Type(IndexType));
- if (response.IsValid)
- {
- indexCnt++;
- }
- else
- {
- this.WriteWarmessage("创建" + IncrementIndexName + "索引,发生异常:SID:" + param.sid.ToString() + "," + response.DebugInformation, "");
- }
- }
- return indexCnt;
- }</span>
4.批量新增、修改索引
- <span style="font-size:14px;"><span style="white-space:pre"> </span>BulkDescriptor descriptor = new BulkDescriptor();</span><pre name="code" class="csharp"><span style="font-size:14px;"><span style="white-space:pre"> </span>descriptor.Index<ES_PUB_Stock>(op => op.Document(esStock));</span></pre><pre name="code" class="csharp"><span style="font-family: Arial, Helvetica, sans-serif;"><span style="font-size:14px;"><span style="white-space:pre"> </span> private int CreateIndex(BulkDescriptor param)</span></span><pre name="code" class="csharp"> {</pre><pre name="code" class="csharp"> int count = 0;
- var result = client.Bulk(param);
- if (!result.Errors)
- count = result.Items.Count();
- return count;
- }</pre>
- <pre></pre>
- <pre></pre>
- <p></p>
- <pre></pre>
- <pre></pre>
- <p></p>
- <p><span style="font-size:14px"><span style="white-space:pre"></span><strong>5.单个删除索引</strong></span></p>
- <pre name="code" class="csharp"><span style="font-size:14px;"> private int DeleteIndex(ES_PUB_Stock param)
- {
- int indexCnt = 0;
- if (param.sid.GetValueOrDefault(0) > 0)
- {
- var response = client.Delete<ES_PUB_Stock>(param.sid, i => i.Index(IndexName).Type(IndexType));
- if (response.IsValid)
- {
- indexCnt++;
- }
- }
- return indexCnt;
- }</span></pre><span style="font-size:14px"><br>
- </span>
- <p></p>
- <p><span style="font-size:14px">按上方所述,即可实现C#对Elasticsearch的操作。</span></p>
- <p><span style="font-size:14px">NEST对Elasticsearch的结构化查询,待下篇......<br>
- </span><br>
- </p>
- <pre></pre>
- <pre></pre>
- </pre>
ElasticSearch.net NEST批量创建修改删除索引完整示例的更多相关文章
- Linux创建修改删除用户和组
Linux 创建修改删除用户和组 介绍 在日常的维护过程中创建用户操作用的相对会多一些,但是在这个过程中涉及到的知识点就不单单就是useradd了,接下来就来详细了解账号管理的相关信息. 用户信息 先 ...
- MySQL查看、创建和删除索引的方法
本文实例讲述了MySQL查看.创建和删除索引的方法.分享给大家供大家参考.具体如下: 1.索引作用 在索引列上,除了上面提到的有序查找之外,数据库利用各种各样的快速定位技术,能够大大提高查询效率.特别 ...
- oracle11g创建修改删除表
oracle11g创建修改删除表 我的数据库名字: ORCL 密码:123456 1.模式 2.创建表 3.表约束 4.修改表 5.删除表 1.模式 set oracle_sid=OR ...
- MySQL进阶11--DDL数据库定义语言--库创建/修改/删除--表的创建/修改/删除/复制
/*进阶 11 DDL 数据库定义语言 库和表的管理 一:库的管理:创建/修改/删除 二:表的管理:创建/修改/删除 创建: CREATE DATABASE [IF NOT EXISTS] 库名; 修 ...
- Cordova之如何用命令行创建一个项目(完整示例)
原文:Cordova之如何用命令行创建一个项目(完整示例) 1. 创建cordova项目 (注意:当第一次创建或编译项目的时候,可能系统会自动下载一些东西,需要一些时间.) 在某个目录下创建cordo ...
- PostgreSQL 查询、创建、删除索引
--查询索引 select * from pg_indexes where tablename='tab1'; --创建索引 tab1_bill_code_index 为索引名, create ind ...
- oracle创建、删除索引等操作
1.创建索引 create index 索引名 on 表名(列名); 2.删除索引 drop index 索引名; 3.创建组合索引 create index 索引名 on 表名(列名1,,列名2); ...
- Linux基础学习-用户的创建修改删除
用户添加修改删除 1 useradd添加用户 添加一个新用户hehe,指定uid为3000,家目录为/home/haha [root@qdlinux ~]# useradd -u 3000 -d /h ...
- hibernate 批量增加 修改 删除
4.2 Hibernate的批量处理 Hibernate完全以面向对象的方式来操作数据库,当程序里以面向对象的方式操作持久化对象时,将被自动转换为对数据库的操作.例如调用Session的delete ...
随机推荐
- Layer Comps
[What is Layer Comps] Designers often create multiple compositions(comps) of a page layout to show c ...
- C#【Thread】Interlocked 轻量级锁
什么说它是轻量级呢?因为它仅对整形数据(即int类型,long也行)进行同步. 具体使用如下表: Interlocked.Increment(ref value) 数值加一(原子性操作) Interl ...
- python操作vmware
import pysphere from pysphere import VIServer host_ip = "200.200.173.45" username = " ...
- Java 设计模式系列(七)桥接模式
Java 设计模式系列(七)桥接模式 桥接模式(Bridge)是一种结构型设计模式.Bridge 模式基于类的最小设计原则,通过使用封装.聚合及继承等行为让不同的类承担不同的职责.它的主要特点是把抽象 ...
- Java07
/* 定义一个类Demo,其中定义一个求两个数据和的方法, 定义一个测试了Test,进行测试. 变量什么时候定义为成员变量: 如果这个变量是用来描述这个类的信息的,那么,该变量就应该定义为成员变量. ...
- 本周MySQL官方verified/open的bug列表(11月15日至11月21日)
本周MySQL verified的bug列表(11月15日至11月21日) 1. Bug #70923 Replication failure on multi-statement INSERT ...
- 在sublime text中添加JavaScript的build-system
-step 1: 下载安装node.js, 并添加到path变量中. -step 2: 在sublime text中新建一个build-system. tools --> build-syste ...
- tp5 根据经纬度计算门店距离 可排序
$branchInfo=Db::name('Branch')->where('b_id','250')->find(); $map['p.cate_id']=array('eq',5); ...
- break,continue以及pass的使用
1.break是提前结束循环 for i in range(1,100): if i%2 == 0: print("wrong") break#直接结束循环,并且不打印下面的pri ...
- iOS7修改UISearchBar的Cancel按钮的颜色和文字
两行代码搞定: [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor ...