【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>
/// <param name="url">ElasticSearch服务器地址</param>
/// <param name="defaultIndex">默认索引名称</param>
/// <param name="defaultType">默认类型</param>
/// <returns></returns>
public static ElasticClient Client(string url, string defaultIndex = "", string defaultType = "")
{
var uri = new Uri(url);
var setting = new ConnectionSettings(uri); if (!string.IsNullOrWhiteSpace(defaultIndex))
{
setting.DefaultIndex(defaultIndex);
} if (!string.IsNullOrWhiteSpace(defaultType))
{
setting.DefaultTypeName(defaultType);
} return new ElasticClient(setting);
} /// <summary>
/// 获取ElasticClient
/// </summary>
/// <param name="urls">ElasticSearch集群地址</param>
/// <param name="defaultIndex">默认索引名称</param>
/// <param name="defaultType">默认类型</param>
/// <returns></returns>
public static ElasticClient Client(string[] urls, string defaultIndex = "", string defaultType = "")
{
var uris = urls.Select(h => new Uri(h)).ToArray();
var pool = new SniffingConnectionPool(uris); var setting = new ConnectionSettings(pool); if (!string.IsNullOrWhiteSpace(defaultIndex))
{
setting.DefaultIndex(defaultIndex);
} if (!string.IsNullOrWhiteSpace(defaultType))
{
setting.DefaultTypeName(defaultType);
} return new ElasticClient(setting);
} /// <summary>
/// 如果同名索引不存在则创建索引
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="client">ElasticClient实例</param>
/// <param name="indexName">要创建的索引名称</param>
/// <param name="numberOfReplicas">默认副本数量,如果是单实例,注意改成0</param>
/// <param name="numberOfShards">默认分片数量</param>
/// <returns></returns>
public static bool CreateIndex<T>(this ElasticClient client, string indexName = "", int numberOfReplicas = , int numberOfShards = ) where T : class
{
if (client.IndexExists(indexName).Exists) return false; var indexState = new IndexState
{
Settings = new IndexSettings
{
NumberOfReplicas = numberOfReplicas, //副本数
NumberOfShards = numberOfShards //分片数
}
}; if (string.IsNullOrWhiteSpace(indexName))
{
indexName = typeof(T).Name.ToLower();
} var result = client.CreateIndex(indexName, c => c.InitializeUsing(indexState).Mappings(ms => ms.Map<T>(m => m.AutoMap())));
return result.Acknowledged;
} /// <summary>
/// 返回一个正序排列的委托
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <returns></returns>
public static Func<SortDescriptor<T>, SortDescriptor<T>> Sort<T>(string field) where T : class
{
return sd => sd.Ascending(field);
} public static Func<SortDescriptor<T>, SortDescriptor<T>> Sort<T>(Expression<Func<T, object>> field) where T : class
{
return sd => sd.Ascending(field);
} /// <summary>
/// 返回一个倒序排列的委托
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <returns></returns>
public static Func<SortDescriptor<T>, SortDescriptor<T>> SortDesc<T>(string field) where T : class
{
return sd => sd.Descending(field);
} public static Func<SortDescriptor<T>, SortDescriptor<T>> SortDesc<T>(Expression<Func<T, object>> field) where T : class
{
return sd => sd.Descending(field);
} /// <summary>
/// 返回一个Must条件集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static List<Func<QueryContainerDescriptor<T>, QueryContainer>> Must<T>() where T : class
{
return new List<Func<QueryContainerDescriptor<T>, QueryContainer>>();
} public static List<Func<QueryContainerDescriptor<T>, QueryContainer>> Should<T>() where T : class
{
return new List<Func<QueryContainerDescriptor<T>, QueryContainer>>();
} /// <summary>
/// 添加Match子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field">要查询的列</param>
/// <param name="value">要查询的关键字</param>
/// <param name="boost"></param>
public static void AddMatch<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
string value, double? boost = null) where T : class
{
musts.Add(d => d.Match(mq => mq.Field(field).Query(value).Boost(boost)));
} public static void AddMatch<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, string value) where T : class
{
musts.Add(d => d.Match(mq => mq.Field(field).Query(value)));
} /// <summary>
/// 添加MultiMatch子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="fields">要查询的列</param>
/// <param name="value">要查询的关键字</param>
public static void AddMultiMatch<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
string[] fields, string value) where T : class
{
musts.Add(d => d.MultiMatch(mq => mq.Fields(fields).Query(value)));
} /// <summary>
/// 添加MultiMatch子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="fields">例如:f=>new [] {f.xxx, f.xxx}</param>
/// <param name="value">要查询的关键字</param>
public static void AddMultiMatch<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> fields, string value) where T : class
{
musts.Add(d => d.MultiMatch(mq => mq.Fields(fields).Query(value)));
} /// <summary>
/// 添加大于子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field">要查询的列</param>
/// <param name="value">要比较的值</param>
public static void AddGreaterThan<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).GreaterThan(value)));
} public static void AddGreaterThan<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).GreaterThan(value)));
} /// <summary>
/// 添加大于等于子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field">要查询的列</param>
/// <param name="value">要比较的值</param>
public static void AddGreaterThanEqual<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).GreaterThanOrEquals(value)));
} public static void AddGreaterThanEqual<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).GreaterThanOrEquals(value)));
} /// <summary>
/// 添加小于子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field">要查询的列</param>
/// <param name="value">要比较的值</param>
public static void AddLessThan<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).LessThan(value)));
} public static void AddLessThan<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).LessThan(value)));
} /// <summary>
/// 添加小于等于子句
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field">要查询的列</param>
/// <param name="value">要比较的值</param>
public static void AddLessThanEqual<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).LessThanOrEquals(value)));
} public static void AddLessThanEqual<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, double value) where T : class
{
musts.Add(d => d.Range(mq => mq.Field(field).LessThanOrEquals(value)));
} /// <summary>
/// 添加一个Term,一个列一个值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field">要查询的列</param>
/// <param name="value">要比较的值</param>
public static void AddTerm<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
object value) where T : class
{
musts.Add(d => d.Term(field, value));
} public static void AddTerm<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, object value) where T : class
{
musts.Add(d => d.Term(field, value));
} /// <summary>
/// 添加一个Terms,一个列多个值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="musts"></param>
/// <param name="field"></param>
/// <param name="values"></param>
public static void AddTerms<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts, string field,
object[] values) where T : class
{
musts.Add(d => d.Terms(tq => tq.Field(field).Terms(values)));
} public static void AddTerms<T>(this List<Func<QueryContainerDescriptor<T>, QueryContainer>> musts,
Expression<Func<T, object>> field, object[] values) where T : class
{
musts.Add(d => d.Terms(tq => tq.Field(field).Terms(values)));
}
}
}
使用方法
/// <summary>
/// 搜索
/// </summary>
/// <param name="input"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
public IActionResult Index(CourseEsSearchInput input, int pageIndex = )
{
pageIndex = pageIndex > ? pageIndex : ; //var musts = new List<Func<QueryContainerDescriptor<CourseEsDto>, QueryContainer>>();
var musts = EsUtil.Must<CourseEsDto>();
if (!string.IsNullOrWhiteSpace(input.School))
{
//musts.Add(c => c.Term(cc => cc.Field("School").Value(input.School)));
musts.AddMatch("school", input.School);
} if (!string.IsNullOrWhiteSpace(input.Key))
{
//musts.Add(c => c.MultiMatch(cc => cc.Fields(ccc => ccc.Fields(ced => new[] {ced.Title, ced.School})).Query(input.Key)));
musts.Add(c => c.MultiMatch(cc => cc.Query(input.Key).Fields(new[] { "title", "school" })));
} var must2 = EsUtil.Must<CourseEsDto>(); if (!string.IsNullOrWhiteSpace(input.Ver1))
{
//musts.Add(c => c.Term(cc => cc.Ver1, input.Ver1));
must2.AddTerm("ver1", input.Ver1);
} if (!string.IsNullOrWhiteSpace(input.Ver2))
{
//musts.Add(c => c.Term(cc => cc.Field(ced => ced.Ver2).Value(input.Ver2)));
must2.AddTerm("ver2", input.Ver2);
} if (!string.IsNullOrWhiteSpace(input.Ver3))
{
//musts.Add(c => c.Term(cc => cc.Field(ced => ced.Ver3).Value(input.Ver2)));
must2.AddTerm("ver3", input.Ver3);
} if (input.PriceStart.HasValue)
{
//musts.Add(c => c.Range(cc => cc.Field(ccc => ccc.Price).GreaterThan((double)input.PriceStart.Value)));
must2.AddGreaterThan("price", (double)input.PriceStart.Value);
} if (input.PriceEnd.HasValue)
{
//musts.Add(c => c.Range(cc => cc.Field(ccc => ccc.Price).LessThanOrEquals((double)input.PriceEnd.Value)));
must2.AddLessThanEqual("price", (double)input.PriceEnd.Value);
} var client = EsUtil.Client("http://127.0.0.1:9200", "course", "doc");
var result = client.Search<CourseEsDto>(sd =>
sd.Query(qcd => qcd
.Bool(cc => cc
.Must(musts)
.Filter(must2))
)
.From( * (pageIndex - ))
.Take()
//.Sort(sdd => sdd.Descending("price"))
.Sort(EsUtil.Sort<CourseEsDto>(c => c.Price))
); var total = result.Total;
var data = result.Documents;
ViewBag.Total = total;
return View(data);
} /// <summary>
/// 创建索引
/// </summary>
/// <returns></returns>
public IActionResult CreateIndex()
{
var result = EsUtil.Client("http://127.0.0.1:9200").CreateIndex<CourseEsDto>("course");
if (result)
{
return Content("创建成功");
}
else
{
return Content("创建失败,可能已存在同名索引");
}
}
【ElasticSearch+NetCore 第二篇】Nest封装的更多相关文章
- ElasticSearch查询 第二篇:文档更新
<ElasticSearch查询>目录导航: ElasticSearch查询 第一篇:搜索API ElasticSearch查询 第二篇:文档更新 ElasticSearch查询 第三篇: ...
- ElasticSearch入门 第二篇:集群配置
这是ElasticSearch 2.4 版本系列的第二篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 E ...
- 【ElasticSearch+NetCore 第一篇】在Windows上安装部署ElasticSearch和ElasticSearch-head
ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是用Java开发的,并作为Apach ...
- ElasticSearch查询 第一篇:搜索API
<ElasticSearch查询>目录导航: ElasticSearch查询 第一篇:搜索API ElasticSearch查询 第二篇:文档更新 ElasticSearch查询 第三篇: ...
- ElasticSearch入门 第一篇:Windows下安装ElasticSearch
这是ElasticSearch 2.4 版本系列的第一篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 E ...
- ElasticSearch入门 第九篇:实现正则表达式查询的思路
这是ElasticSearch 2.4 版本系列的第九篇: ElasticSearch入门 第一篇:Windows下安装ElasticSearch ElasticSearch入门 第二篇:集群配置 E ...
- Elasticsearch第五篇:PlainElastic.Net 操作 Elasticsearch
再次强调,我安装的Elasticsearch 版本是 7.8.0 ,C# 操作 Elasticsearch 的驱动有 NEST.Elasticsearch.net .PlainElastic.Net ...
- 【OpenGL】第二篇 Hello OpenGL
---------------------------------------------------------------------------------------------------- ...
- 第二篇 :微信公众平台开发实战Java版之开启开发者模式,接入微信公众平台开发
第一部分:微信公众号对接的基本介绍 一.填写服务器配置信息的介绍 登录微信公众平台官网后,进入到公众平台后台管理页面. 选择 公众号基本设置->基本配置 ,点击“修改配置”按钮,填写服务器地址( ...
随机推荐
- puml 用于代码注释
notebook 笔记本 @startuml rectangle sql_decode.py{ object SQLDataset object Name SQLDataset : meta = &q ...
- python日志实时分析
python随着人工智能的发展,越来越火热.但其实python在运维测试方面,也是一把利器. 最近就碰到了个需求,就顺手写了个python程序.用惯了go,不过发现python好像更简单点 :-) 涉 ...
- 5.创建执行线程的方式之三 :实现Callable 接口
Callable 接口 一.Java 5.0 在 java.util.concurrent 提供了 一个新的创建执行线程的方式(之前有继承Thread 和 实现Runnable):Callable 接 ...
- python点击短信验证码
代码如下 : import requestsimport time# 手机号码tel=1381380000# 请求地址url="http://192.168.100.101:8080/api ...
- 完整的ELK+filebeat+kafka笔记
之前有写过elasticsearch集群和elk集群的博客, 都是基于docker的,使用docker-compose进行编排(K8S暂未掌握) 三台服务器搭建es集群:https://www.cnb ...
- python采集websocket实时数据
之前大部分的数据采集基本都是http的,也一直对如何采集websocket的实时数据有疑问,不知道入从哪里入手,一筹莫展,今天在知乎上看到了一篇采集websocket的文章,讲的很透彻 终于把这个疑问 ...
- BCB 编写服务程序的一个注意事项
BCB编写服务,install报错的一个问题 今天编写了一个服务,最后INSTALL 的时候报错,如图: 经过近1小时的比较(俺过去写例子),居然无意中设置了一个属性 ...
- golang 2 ways to delete an element from a slice
2 ways to delete an element from a slice yourbasic.org/golang Fast version (changes order) a := []st ...
- FFT/FWT
最近舟游疯狂出货,心情很好~ FFT FWT 快速傅里叶变换(FFT) 具体的推导见这篇:胡小兔 - 小学生都能看懂的FFT!!! (写的很好,不过本小学生第一次没看懂0.0) 总结下关键内容 ~ P ...
- kubectl 自动补全
kubectl 这个命令行工具非常重要,与之相关的命令也很多,我们也记不住那么多的命令,而且也会经常写错,所以命令自动补全是很有必要的,kubectl 工具本身就支持自动补全,只需简单设置一下即可. ...