【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版之开启开发者模式,接入微信公众平台开发
第一部分:微信公众号对接的基本介绍 一.填写服务器配置信息的介绍 登录微信公众平台官网后,进入到公众平台后台管理页面. 选择 公众号基本设置->基本配置 ,点击“修改配置”按钮,填写服务器地址( ...
随机推荐
- python 切换虚拟环境
每次电脑重启后,都要切入虚拟环境,命令总是忘记.如果使用IDE,可以指定interpeter方便的切换. 首先conda info --env 查看当前有几个环境 激活/禁用环境 source ac ...
- java调用.net的webservice接口
要调用webservice,首先得有接口,用已经写好的接口地址在myEclipse的目标project中,右键->new web service client-> 选择JAX-WS方式,点 ...
- MMU简介
MMU(Memory Management Unit)内存管理单元 负责虚拟地址到物理地址的映射,并提供硬件机制的内存访问权限检查.内存访问权限的检查可以保护每个进程所用的内存不会被其他进程所破坏 地 ...
- shell 数组介绍
平时的定义a=1;b=2;c=3,变量如果多了,再一个一个定义很繁琐,并且取变量值也很累.简单的说,数组就是各种数据类型的元素按一定顺序排列的集合. 数组就是把有限个元素变量或数组用一个名字命名,然后 ...
- 【hadoop】细读MapReduce的工作原理
前言:中秋节有事外加休息了一天,今天晚上重新拾起Hadoop,但感觉自己有点烦躁,不知后续怎么选择学习Hadoop的方法. 干脆打开电脑,决定: 1.先将Hadoop的MapReduce和Yarn基本 ...
- 【Java基础-实验7】Banking_7 -添加银行透支扣款系统的 thorw异常机制
实验基本要求: 实验题目 7:(在6基础上修改) 将建立一个 OverdraftException 异常,它由 Account 类的withdraw()方法 抛出. 实验目的: 自定义异常 实验说明: ...
- #2002 Cannot log in to the MySQL server, PHPMyAdmin/MySQL
改完会可能会出现1045的错误 在phpStudy中,其他选项菜单——mysql工具——重置密码,即可
- es批量导入进一对多的数据
es批量导入进一对多的数据 我有一个产品表 一个产品对应多个属性名 一个属性名对应多个属性值 一个产品还对应一个分类名称 控制层 @ApiOperation(value = "导入所有 ...
- JSP运行原理以及执行过程源码分析
我们在开发JavaWeb的过程中,可能有过这样的疑问,当我们编写jsp页面时,不用引用不用创建就可以使用request.session.application对象,当使用浏览器访问JSP页面时,查看页 ...
- list 对像排序
在C#的List操作中,针对List对象集合的排序我们可以使用OrderBy.OrderByDescending.ThenBy.ThenByDescending等方法按照特定的对象属性进行排序,其中O ...