Elasticsearch.net项目
Elasticsearch.net项目实战
https://www.cnblogs.com/lucky_hu/p/9746736.html
elasticsearch.net项目实战
@智客幸达
目录
Elasticsearch+kibana
环境搭建
windows 10环境配置
安装Elasticsearch
head安装(非必需)
安装kibana
DSL的基本使用
增加
修改
查询
删除
Elasticsearch .Net
Low level client基本使用
项目实战
总结
参考
Elasticsearch是一个基于Apache Lucene(TM)的开源搜索引擎。无论在开源还是专有领域,Lucene可以被认为是迄今为止最
先进、性能最好的、功能最全的搜索引擎库。
一说到全文搜索,lucene久负盛名。早年间,因为项目需要,接触过一个叫盘古分词的开源项目,借助其中的分词实现了分词搜索的功能。而盘古分词就是lucence的.NET版本。据说这个开源项目已经恢复更新并支持. NET Core,有兴趣的童鞋可以去围观一下(https://github.com/LonghronShen/Lucene.Net.Analysis.PanGu/tree/netcore2.0)。
我想很多童鞋都听过ELK,ELK是Elasticsearch、Logstash、Kibana。正好公司运维同事引入了这样一套体系,用于建立集中式日志收集系统,将所有节点上的日志统一收集,管理,访问。虽然能够从一定程度上解决基本的问题,但是原生的kibana界面和查询方式都不够友好,很难推向广大的开发人员。于是我在想,我们是否可以利用这个开源的库集成到运维自动化平台当中,让这把利剑发挥出更大的价值。
一、环境搭建
本文是基于windows 10操作系统的es环境的搭建。
java环境安装
由于es是java语言开发的,所以这里要安装java环境。
jdk下载:
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
安装完成之后就是配置环境变量:
查看是否安装成功:
2.安装Elasticsearch
Elasticsearch版本已经比较多,初学者可能比较懵。特别是在安装head和Kibana的时候,如果版本不匹配,往往会导致无法使用。这里使用的是elasticsearch-5.6.11版本。
elasticsearch-5.6.11下载:
https://www.elastic.co/downloads/past-releases/elasticsearch-5-6-11
解压到C:\ELk 备用。
3.head安装(非必需)
es 4.x 版本安装head很简单,只需下载head插件解压到指定目录即可。es 5.x+需要借助node安装。
head下载:
https://github.com/mobz/elasticsearch-head
解压到C:\ELk\elasticsearch-5.6.11
node下载:
https://nodejs.org/dist/v8.12.0/node-v8.12.0-win-x64.zip
安装node
检查node和npm是否安装成功
path环境变量末尾 会自动增加 C:\Program Files\nodejs
安装 phantomjs
官网:http://phantomjs.org/下载【配置环境变量】
安装grunt
npm install -g grunt-cli
执行C:\ELk\elasticsearch-5.6.11\bin\elasticsearch.bat
执行命令启动 head
浏览器访问:http://localhost:9100/
4.安装kibana
导致为止,其实elasticsearch自身已经安装完成。通过Head就能很方便的操作es,但是kibana集成了head类似功能,并提供了更加友好的访问界面。
kibana-5.6.9-windows-x86下载:
https://www.elastic.co/downloads/past-releases/kibana-5-6-9
下载之后,解压到C:\ELk\kibana-5.6.9-windows-x86
执行C:\ELk\kibana-5.6.9-windows-x86\bin\kibana.bat
浏览器访问:http://localhost:5601
二、DSL的基本使用
elasticsearch也像mysql一样提供了专门的语法来操作数据。Elasticsearch provides a full Query DSL (Domain Specific Language) based on JSON to define queries.
创建文档
PUT people/person/1?op_type=create
{
"user" : "kimchy",
"post_date" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}
修改
POST /user/guest/20/_update
{
"doc": {
"RealName":"LukyHuu20"
}
}
查询
GET /user/guest/_search
{
"query": {
"match": {
"Id":22
}
}
}
删除
DELETE /user/guest/15
{
}
三、Elasticsearch .Net
elasticsearch是以restfulAPI方式对外提供接口,并提供客户端给多种语言使用。Elasticsearch uses standard RESTful APIs and JSON. We also build and maintain clients in many languages such as Java, Python, .NET, SQL, and PHP. Plus, our community has contributed many more. They’re easy to work with, feel natural to use, and, just like Elasticsearch, don't limit what you might want to do with them.
参考(https://www.elastic.co/products/elasticsearch)
1.Low level client基本使用
本文是介绍ES的.NET客户端,Elasticsearch .Net - Low level client[5.x]
通过引入对应的版本的客户端,便可通过C#操作ES。参考(https://www.elastic.co/guide/en/elasticsearch/client/net-api/5.x/elasticsearch-net.html)
连接
var settings = new ConnectionConfiguration(new Uri("http://example.com:9200"))
.RequestTimeout(TimeSpan.FromMinutes(2));
var lowlevelClient = new ElasticLowLevelClient(settings);
插入文档
var indexResponse = lowlevelClient.Index<byte[]>("user", "guest", user.Id.ToString(), user);
byte[] responseBytes = indexResponse.Body;
更新文档
var searchResponse = lowlevelClient.Update("user", "guest", id.ToString(), new
{
doc = new
{
RealName = realname,
Description = description
}
});
bool successful = searchResponse.Success;
查询
var searchResponse = lowlevelClient.Search("user", "guest", new
{
query = new
{
match = new
{
Id = id
}
}
});
bool successful = searchResponse.Success;
删除
var searchResponse = lowlevelClient.Delete("user", "guest", id.ToString());
bool successful = searchResponse.Success;
2.项目实战
前面大致介绍了ES的安装和基本使用。那么,如何在项目中落地呢?
使用nuget安装Elasticsearch.Net 5.6.4
Install-Package Elasticsearch.Net -Version 5.6.4
安装完后,
基本的增删该查在项目中的实现上面已经有所介绍,这里重点讲一下查询:
笔者使用的.NET MVC5 Web框架,对于返回的结果笔者做了一个简单封装:
public class ESearchRoot
{
///
///
///
public int took { get; set; }
///
///
///
public string timed_out { get; set; }
///
///
///
public _shards _shards { get; set; }
///
///
///
public Hits hits { get; set; }
}
public class _shards
{
/// <summary>
///
/// </summary>
public int total { get; set; }
/// <summary>
///
/// </summary>
public int successful { get; set; }
/// <summary>
///
/// </summary>
public int skipped { get; set; }
/// <summary>
///
/// </summary>
public int failed { get; set; }
}
public class HitsItem<T>
{
/// <summary>
///
/// </summary>
public string _index { get; set; }
/// <summary>
///
/// </summary>
public string _type { get; set; }
/// <summary>
///
/// </summary>
public string _id { get; set; }
/// <summary>
///
/// </summary>
public string _score { get; set; }
/// <summary>
///
/// </summary>
public T _source { get; set; }
/// <summary>
///
/// </summary>
public List<int> sort { get; set; }
/// <summary>
///
/// </summary>
public Highlight highlight { get; set; }
}
public class Hits<T>
{
/// <summary>
///
/// </summary>
public int total { get; set; }
/// <summary>
///
/// </summary>
public string max_score { get; set; }
/// <summary>
///
/// </summary>
public List<HitsItem<T>> hits { get; set; }
}
public class Highlight
{
/// <summary>
///
/// </summary>
public List<string> Description { get; set; }
}
因为soure返回的对象是不定的,所以使用了泛型。
本项目soure对应的类,user:
///
///
///
public class User
{
///
///
///
public string Account { get; set; }
///
///
///
public string Phone { get; set; }
///
///
///
public string Email { get; set; }
///
///
///
public string RealName { get; set; }
///
///
///
public string CanReview { get; set; }
///
///
///
public string CanExcute { get; set; }
///
///
///
public string Avatar { get; set; }
///
///
///
public string IsUse { get; set; }
///
///
///
public int Id { get; set; }
///
///
///
public string Name { get; set; }
///
///
///
public string Description { get; set; }
///
///
///
public DateTime CreateTime { get; set; }
///
///
///
public DateTime ModifyTime { get; set; }
}
项目使用了带条件的分页查询:
public List GetBySomeWhere(string keyword, int limit, int pageSize, out int total)
{
List users = new List();
total = 0;
try
{
var settings = new ConnectionConfiguration(new Uri("http://localhost:9200/"))
.RequestTimeout(TimeSpan.FromMinutes(2));
var lowlevelClient = new ElasticLowLevelClient(settings);
//根据不同的参数 来构建不同的查询条件
var request = new object();
if (!String.IsNullOrEmpty(keyword))
{
request = new
{
from = limit,
size = pageSize,
query = new
{
match = new
{
Description = keyword
}
},
highlight = new
{
fields = new
{
Description = new { }
}
},
sort = new
{
Id = new
{
order = "desc"
}
}
};
}
else
{
request = new
{
from = limit,
size = pageSize,
query = new
{
match_all = new
{
}
},
highlight = new
{
fields = new
{
Description = new { }
}
},
sort = new
{
Id = new
{
order = "desc"
}
}
};
}
var searchResponse = lowlevelClient.Search<string>("user", "guest", request);
bool successful = searchResponse.Success;
var responseJson = searchResponse.Body;
if (!successful)
{
return users;
}
ESearchRoot<User> root = JsonHelper.JSONStringObject<ESearchRoot<User>>(responseJson);
if (root != null)
{
total = root.hits.total;
foreach (HitsItem<User> item in root.hits.hits)
{
if (item._source != null)
{
string highlightDescription = String.Empty;
StringBuilder sbDs = new StringBuilder();
if (item.highlight != null && item.highlight.Description.Count > 0)
{
//ighlightDescription = item.highlight.Description[0];
foreach (var d in item.highlight.Description)
{
sbDs.Append(d);
}
highlightDescription = sbDs.ToString();
}
AdminUser user = new AdminUser
{
Id = item._source.Id,
RealName = item._source.RealName,
Account = item._source.Account,
Email = item._source.Email,
Phone = item._source.Phone,
//IsUse=item._source.IsUse,
Avatar = item._source.Avatar,
Description = item._source.Description,
HighlightDescription = highlightDescription,
CreateTime = item._source.CreateTime,
ModifyTime = item._source.ModifyTime
};
users.Add(user);
}
}
}
return users;
}
catch (ElasticsearchClientException ex)
{
//Log4Helper.Error
}
return users;
}
项目最终的效果如下:
四、总结
elasticsearch是很强大的开源工具,在实现全文搜索上有其独到之处,也是大数据的分析方面利器,值得大家深入去研究和实践。
五、参考
Elasticsearch权威指南
Elasticsearch.Net 5.x
Elasticsearch Reference [5.6] » Document APIs
elasticsearch-net-example
ElasticSearch安装及HEAD插件配置
Elasticsearch.net项目的更多相关文章
- Elasticsearch.net项目实战
elasticsearch.net项目实战 目录 Elasticsearch+kibana 环境搭建 windows 10环境配置 安装Elasticsearch head安装(非必需) 安装kiba ...
- 使用elasticsearch启动项目报错failed to load elasticsearch nodes 。。。。。No type specified for field [name]
failed to load elasticsearch nodes .....No type specified for field [name]翻译: 加载ElasticSearch节点失败... ...
- Lucene/ElasticSearch 学习系列 (1) 为什么学,学什么,怎么学
为什么学 <What I wish I knew When I was 20>这本书给了我很多启发.作者在书中提到,Stanford 大学培养人才的目标是 ”T形人才“:精通某个领域,但对 ...
- 开源搜索引擎评估:lucene sphinx elasticsearch
开源搜索引擎评估:lucene sphinx elasticsearch 开源搜索引擎程序有3大类 lucene系,java开发,包括solr和elasticsearch sphinx,c++开发,简 ...
- 使用Java High Level REST Client操作elasticsearch
Java高级别REST客户端(The Java High Level REST Client)以后简称高级客户端,内部仍然是基于低级客户端.它提供了更多的API,接受请求对象作为参数并返回响应对象,由 ...
- Spring Boot 整合 elasticsearch
一.简介 我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的 首选.他可以快速的存储.搜索和分析海量数据.Spring Boot通过整合Spring Data E ...
- Elasticsearch Query DSL 整理总结(一)—— Query DSL 概要,MatchAllQuery,全文查询简述
目录 引言 概要 Query and filter context Match All Query 全文查询 Full text queries 小结 参考文档 引言 虽然之前做过 elasticse ...
- Elasticsearch Java Rest Client API 整理总结 (一)——Document API
目录 引言 概述 High REST Client 起步 兼容性 Java Doc 地址 Maven 配置 依赖 初始化 文档 API Index API GET API Exists API Del ...
- 【spring boot】【elasticsearch】spring boot整合elasticsearch,启动报错Caused by: java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8
spring boot整合elasticsearch, 启动报错: Caused by: java.lang.IllegalStateException: availableProcessors ], ...
随机推荐
- 系统OOM复位定位
定位OOM的工具: 1.多次收集Thread Dump信息kill -3 PID通过对比分析heap 对象信息和Thread信息来定位 2.通过 -Xloggc:D:/gc.log -XX:+He ...
- 在 Mac OS 上编译 OBS
本文转自:在 Mac OS 上编译 OBS | www.samirchen.com 安装环境 第一步,做准备工作,安装编译 OBS 所需要的环境,流程如下: // 给当前用户添加 /usr/local ...
- iptables配置顺序-两条规则会忽略后边的
oracle在centos本机能够正常访问,关闭防火墙也能够远程访问,但是一旦开启防火墙则不能远程访问 尝试添加规则iptables -A INPUT -m state --state NEW -m ...
- ASP.NET MVC CheckBoxFor的int to bool
当我们使用CheckBoxFor类型需要使用bool ,可以将 int转换成bool <div class="form-group"> <label class= ...
- 20145201 实验三 敏捷开发与XP实践
实验内容 XP基础 XP核心实践 相关工具 实验步骤 (一)敏捷开发与XP 软件工程是把系统的.有序的.可量化的方法应用到软件的开发.运营和维护上的过程.软件工程包括下列领域:软件需求分析.软件设计. ...
- uitableview 侧滑删除
https://github.com/MortimerGoro/MGSwipeTableCell
- [UOJ210]寻找罪犯
2-sat神题.. 告诉是2-sat我也完全想不到正解. 看了看题解其实一步步分析也不算很难 这个题首先是要围绕每个人是否是犯人和每句话是否是真话来思考 首先要明确的是: 1.好人不说谎话 2.说了谎 ...
- 初涉Rx套餐 之RxBinding(让你的事件流程更清晰)
转载请注明出处:王亟亟的大牛之路 最近下班回家都在WOW,周末就爆肝,感觉人都要GO DIE了,昨天下午看了看RxBinding相关的功能感觉还是蛮强大的,所提供的API也是相当丰富(基本Rx套餐都是 ...
- zabbix监控使用
zabbix监控 通过导入/导出zabbix配置文件,我们可以将自己写好的模板等配置在网络上分享,我们也可以导入网络上分享的配置文件,配置文件有两种格式,分为xml与json,通过zabbix管理界面 ...
- LOJ 一本通一句话题解系列:
第一部分 基础算法 第 1 章 贪心算法 1):「一本通 1.1 例 1」活动安排:按照结束时间排序,然后扫一遍就可以了. 2):「一本通 1.1 例 2」种树:首先要尽量的往区间重叠的部分种树,先按 ...