赞
踩
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。[来源于百度百科]
官方网址:https://www.elastic.co/cn/products/elasticsearch
文档地址:https://www.elastic.co/guide/en/elasticsearch/reference/index.html
Github :https://github.com/elastic/elasticsearch
归结为两点:elasticsearch是一个基于Lucene的高扩展的分布式搜索服务器,支持开箱即用;elasticsearch隐藏了Lucene的复杂性,对外提供Restful 接口来操作索引、搜索。
突出优点:扩展性好,可部署上百台服务器集群,处理PB级数据;近实时的去索引数据、搜索数据。各种全文索引工具对比
ES的索引采用的是倒排索引的方式,除了存文档之外还存储了分词数据集,每个词都会记录与之关联的文档。在检索的时候就很方便的通过词来找到对应的文档。
Elasticsearch 使用的是标准的 RESTful 风格的 API 和 JSON。此外,还构建和维护了很多其他语言的客户端,例如 Java、Python、.NET、SQL 和 PHP以及其他社区客户端。这些客户端使用起来简单自然,而且就像 Elasticsearch 一样,不会对您的使用方式进行限制。
安装配置:
1、新版本要求至少jdk1.8以上。
2、支持tar、zip、rpm等多种安装方式。
在windows下开发建议使用ZIP安装方式。
3、支持docker方式安装
详细参见:https://www.elastic.co/guide/en/elasticsearch/reference/current/install-elasticsearch.html
下载并解压 ES: Elasticsearch 6.2.4
ES的配置文件的地址根据安装形式的不同而不同:使用zip、tar安装,配置文件的地址在安装目录的config下;使用RPM安装,配置文件在/etc/elasticsearch下;使用MSI安装,配置文件的地址在安装目录的config下,并且会自动将config目录地址写入环境变量ES_PATH_CONF。
配置文件如下:
配置格式是YAML,可以采用如下两种方式:
#设置为true可以锁住ES使用的内存,避免内存与swap分区交换数据。 bootstrap.memory_lock: false #配置elasticsearch的集群名称,默认是elasticsearch。建议修改成一个有意义的名称。 cluster.name: es-learning #设置对外服务的http端口,默认为9200。 http.port: 9200 #设置绑定主机的ip地址,设置为0.0.0.0表示绑定任何ip,允许外网访问,生产环境建议设置为具体的ip。 network.host: 0.0.0.0 # 指定该节点是否存储索引数据,默认为true。 node.data: true #ingest node主要是通过使用ingest pipeline来对文档在索引之前进行转换或者增强。 node.ingest: true #指定该节点是否有资格被选举成为master结点,默认是true,如果原来的master宕机会重新选举新的master。 node.master: true #单机允许的最大存储结点数,通常单机启动一个结点建议设置为1,开发环境如果单机启动多个节点可设置大于1. node.max_local_storage_nodes: 1 #节点名,通常一台物理服务器就是一个节点,es会默认随机指定一个名字,建议指定一个有意义的名称, #方便管理一个或多个节点组成一个cluster集群,集群是一个逻辑的概念,节点是物理概念。 node.name: learning-node1 #path.conf: 设置配置文件的存储路径,tar或zip包安装默认在es根目录下的config文件夹,rpm安装默认在/etc/elasticsearch #path.plugins: 设置插件的存放路径,默认是es根目录下的plugins文件夹 #设置索引数据的存储路径,默认是es根目录下的data文件夹,可以设置多个存储路径,用逗号隔开。 path.data: D:\Elastic\6.2.4\data #设置日志文件的存储路径,默认是es根目录下的logs文件夹 path.logs: D:\Elastic\6.2.4\logs #集群结点之间通信端口 transport.tcp.port: 9300 #设置集群中master节点的初始列表。 #discovery.zen.ping.unicast.hosts: ["0.0.0.0:9300", "0.0.0.0:9301"] #设置ES自动发现节点连接超时的时间,默认为3秒,如果网络延迟高可设置大些。 #discovery.zen.ping.timeout: 3s #主结点数量的最少值 ,此值的公式为:(master_eligible_nodes / 2) + 1 ,比如:有3个符合要求的主结点,那么这里要设置为2。 #discovery.zen.minimum_master_nodes: 1 #如果启用了 HTTP 端口,那么此属性会指定是否允许跨源 REST 请求。 http.cors.enabled: true #跨域访问允许的域名地址 http.cors.allow-origin: /.*/
在jvm.options中设置最小及最大的JVM堆内存大小:-Xms、-Xmx 建议两个值设置为相等且不超过物理内存的一半。
日志文件设置,ES使用log4j,采用默认配置即可,可以更具不同环境需要修改日志级别的配置。
在linux上根据系统资源情况,可将每个进程最多允许打开的文件数设置大些。
#查询当前文件数
su limit -n
#设置limit的值
sudo ulimit ‐n 65536
也可以通过修改 /etc/security/limits.conf 添加elasticsearch ‐ nofile 65536
进行持久设置.
进入bin目录,在cmd下运行:elasticsearch.bat
浏览器输入:http://localhost:9200
显示结果如下(配置不同内容则不同)说明 ES启动成功:
{
"name" : "learning-node1",
"cluster_name" : "es-learning",
"cluster_uuid" : "bOyFIKYdT1Cya41fqsW0VQ",
"version" : {
"number" : "6.2.4",
"build_hash" : "ccec39f",
"build_date" : "2019-06-12T20:37:28.497551Z",
"build_snapshot" : false,
"lucene_version" : "7.2.1",
"minimum_wire_compatibility_version" : "5.6.0",
"minimum_index_compatibility_version" : "5.0.0"
},
"tagline" : "You Know, for Search"
}
head插件是ES的一个可视化管理插件,用来监视ES的状态,并通过head客户端和ES服务进行交互,比如创建映射、创建索引等,head的项目地址在https://github.com/mobz/elasticsearch-head 。从ES6.0开始,head插件支持使用node.js运行。安装node.js
2、下载head并运行
git clone git://github.com/mobz/elasticsearch-head.git
cd elasticsearch-head
npm install
npm run start
open http://localhost:9100/
就是一个简单的图形操作界面,使用方式就不介绍了。
ES作为一个索引及搜索服务,对外提供丰富的REST接口,新使用几个快速入门的实例对ES的使用方法及流程有个初步的认识。
ES的索引库是一个逻辑概念,它包括了分词列表及文档列表,同一个索引库中存储了相同类型的文档。它就相当于MySQL中的表,或相当于Mongodb中的集合。关于索引这个语:
下边介绍两种创建索引库的方法,它们的工作原理是相同的,都是客户端向ES服务发送命令。
put http://localhost:9200/索引库名称
{
"settings":{
"index":{
"number_of_shards":1,
"number_of_replicas":0
}
}
}
在索引中每个文档都包括了一个或多个field,创建映射就是向索引库中创建field的过程,下边是document和field与关系数据库的概念的类比:
文档(Document) —— Row记录
字段(Field) —— Columns 列
注意:6.0之前的版本有type(类型)概念,type相当于关系数据库的表,ES官方将在ES9.0版本中彻底删除type。
上边讲的创建索引库相当于关系数据库中的数据库还是表?
请求命令如下:
post http://localhost:9200/索引库名称 /类型名称/_mapping
创建类型为es_index的映射,共包括两个字段:name、description
由于ES6.0版本还没有将type彻底删除,所以暂时把type起一个没有特殊意义的名字。
post 请求:http://localhost:9200/es_index/doc_type/_mapping
表示:在 es_index索引库下的doc_type类型下创建映射。doc_type是类型名,可以自定义,在ES6.0中要弱化类型的概念,给它起一个没有具体业务意义的名称。
{
"properties": {
"name": {
"type": "text"
},
"description": {
"type": "text"
}
}
}
ES中的文档相当于MySQL数据库表中的记录。
请求方式:POST或PUT (如果不指定id值ES会自动生成ID) http://localhost:9200/es_index/doc_type/id
http://localhost:9200/es_index/doc_type/6666
{
"name":"全文检索-Elasticearch",
"description":"Elasticsearch是一个实时的分布式搜索和分析引擎。它可以帮助你用前所未有的速度去处理大规模数据。它可以用于全文搜索,结构化搜索以及分析,当然你也可以将这三者进行组合。"
}
1、根据id查询文档
请求方式:GET http://localhost:9200/es_index/doc_type/6666
2、查询所有记录
请求方式:GET http://localhost:9200/es_index/doc_type/_search
2、查询名称中包括 “全文” 的的记录
请求方式:GET http://localhost:9200/es_index/doc_type/_search?q=name:全文
分析以下查询结果:
{ "took": 77, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": 1, "max_score": 1.179499, "hits": [ { "_index": "es_index", "_type": "doc_type", "_id": "6666", "_score": 1.179499, "_source": { "name": "全文检索-Elasticearch", "description": "Elasticsearch是一个实时的分布式搜索和分析引擎。它可以帮助你用前所未有的速度去处理大规模数据。它可以用于全文搜索,结构化搜索以及分析,当然你也可以将这三者进行组合。" } } ] } }
在添加文档时会进行分词,索引中存放的就是一个一个的词(term),当你去搜索时就是拿关键字去匹配词,最终找到词关联的文档。
测试当前索引库使用的默认分词器:
请求方式POST : http://localhost:9200/_analyze
{"text":"测试分词器"}
当前索引库使用的默认分词器对中文就是单字分词。
使用IK分词器可以实现对中文分词的效果。
下载IK分词器:(Github地址:https://github.com/medcl/elasticsearch-analysis-ik)
解压,并将解压的文件拷贝到ES安装目录的plugins下的ik目录下
指定IK分词,再次测试分词效果
{"text":"测试分词器","analyzer":"ik_max_word" }
ik分词器有两种分词模式:ik_max_word和ik_smart模式。
{ "tokens": [ { "token": "中华人民共和国", "start_offset": 0, "end_offset": 7, "type": "CN_WORD", "position": 0 }, { "token": "中华人民", "start_offset": 0, "end_offset": 4, "type": "CN_WORD", "position": 1 }, { "token": "中华", "start_offset": 0, "end_offset": 2, "type": "CN_WORD", "position": 2 }, { "token": "华人", "start_offset": 1, "end_offset": 3, "type": "CN_WORD", "position": 3 }, { "token": "人民共和国", "start_offset": 2, "end_offset": 7, "type": "CN_WORD", "position": 4 }, { "token": "人民", "start_offset": 2, "end_offset": 4, "type": "CN_WORD", "position": 5 }, { "token": "共和国", "start_offset": 4, "end_offset": 7, "type": "CN_WORD", "position": 6 }, { "token": "共和", "start_offset": 4, "end_offset": 6, "type": "CN_WORD", "position": 7 }, { "token": "国", "start_offset": 6, "end_offset": 7, "type": "CN_CHAR", "position": 8 } ] }
如果要让分词器支持一些专有词语,可以自定义词库。iK分词器自带一个main.dic的文件,在插件的config目录中。我们可以在上边的目录中新建一个自定义的词库文件(注意文件格式为utf-8(不要选择utf-8 BOM)),然后可以在
IKAnalyzer.cfg.xml中配置。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>IK Analyzer 扩展配置</comment>
<!--用户可以在这里配置自己的扩展字典 -->
<entry key="ext_dict"></entry>
<!--用户可以在这里配置自己的扩展停止词字典-->
<entry key="ext_stopwords"></entry>
<!--用户可以在这里配置远程扩展字典 -->
<!-- <entry key="remote_ext_dict">words_location</entry> -->
<!--用户可以在这里配置远程扩展停止词字典-->
<!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>
上边章节安装了ik分词器,如果在索引和搜索时去使用ik分词器呢?如何指定其它类型的field,比如日期类型、数值类型等。
本章节学习各种映射类型及映射维护方法。
1、查询所有索引的映射:
GET: http://localhost:9200/_mapping
2、创建映射
post 请求:http://localhost:9200/es_index/doc_type/_mapping
{
"properties": {
"name": {
"type": "text"
},
"description": {
"type": "text"
},
"type": {
"type": "keyword"
}
}
}
3、更新映射
映射创建成功可以添加新字段,已有字段不允许更新。
4、删除映射
通过删除索引来删除映射。
ES6.2核心的字段类型如下:
字符串包括 text和keyword两种类型。text类型的可以设置的属性如下:
"name":{
"type":"text",
"analyzer":"ik_max_word",
"search_analyzer":"ik_smart"
}
"logo":{
"type":"text",
"index":false
}
上边介绍的 text文本字段在映射时要设置分词器,keyword字段为关键字字段,通常搜索keyword是按照整体搜索,所以创建keyword字段的索引时是不进行分词的,比如:邮政编码、手机号码、身份证等。keyword字段通常用于过虑、排序、聚合等。
"mobile":{
"type":"keyword"
}
日期类型不用设置分词器,通常用于排序。
{
"timestamp":{
"type":"date",
"format":"yyyy‐MM‐dd HH:mm:ss || yyyy‐MM‐dd"
}
}
ES6.2数值类型官方文档
原则:尽量选择范围小的类型,提高搜索效率;对于浮点数尽量用比例因子,比如一个价格字段,单位为元,我们将比例因子设置为100这在ES中会将你传入的数值乘100后存储,映射如下:
{
"price":{
"type":"scaled_float",
"scaling_factor":100
}
}
如果输入的价格是23.456,ES会将23.456乘以100再取一个接近原始值的数,得出2346。使用比例因子的好处是整型比浮点型更易压缩,节省磁盘空间。如果比例因子不适合,则从下表选择范围小的去用:
ES提供多种不同的客户端:
1、TransportClient ES提供的传统客户端,官方计划8.0版本删除此客户端。
2、RestClient 是官方推荐使用的,它包括两种:Java Low Level REST Client和 Java High Level REST Client。ES在6.0之后提供 Java High Level REST Client, 两种客户端官方更推荐使用 Java High Level REST Client,不过当
前它还处于完善中,有些功能还没有。本文准备采用 Java High Level REST Client,如果它有不支持的功能,则使用Java Low Level REST Client。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch‐rest‐high‐level‐client</artifactId>
<version>6.2.4</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.4</version>
</dependency>
server:
port: ${port:9090}
spring:
application:
name: es‐search‐service
elasticsearch:
hostlist: ${eshostlist:127.0.0.1:9200} #多个结点中间用逗号分隔
package com.qqxhb.search.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticsearchConfig { @Value("${elasticsearch.hostlist}") private String hostlist; @Bean public RestHighLevelClient restHighLevelClient(){ //解析hostlist配置信息 String[] split = hostlist.split(","); //创建HttpHost数组,其中存放es主机和端口的配置信息 HttpHost[] httpHostArray = new HttpHost[split.length]; for(int i=0;i<split.length;i++){ String item = split[i]; httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http"); } //创建RestHighLevelClient客户端 return new RestHighLevelClient(RestClient.builder(httpHostArray)); } //项目主要使用RestHighLevelClient,对于低级的客户端暂时不用 @Bean public RestClient restClient(){ //解析hostlist配置信息 String[] split = hostlist.split(","); //创建HttpHost数组,其中存放es主机和端口的配置信息 HttpHost[] httpHostArray = new HttpHost[split.length]; for(int i=0;i<split.length;i++){ String item = split[i]; httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http"); } return RestClient.builder(httpHostArray).build(); } }
创建索引: put http://localhost:9200/索引名称
{
"settings":{
"index":{
"number_of_shards":1,
"number_of_replicas":0
}
}
}
创建映射: put http://localhost:9200/索引库名称 /类型名称/_mapping
{ "properties": { "name": { "type": "text", "analyzer":"ik_max_word", "search_analyzer":"ik_smart" }, "description": { "type": "text", "analyzer":"ik_max_word", "search_analyzer":"ik_smart" }, "studymodel": { "type": "keyword" }, "price": { "type": "float" }, "timestamp": { "type": "date", "format": "yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd||epoch_millis" } } }
@SpringBootTest @RunWith(SpringRunner.class) public class TestIndex { @Autowired RestHighLevelClient client; @Autowired RestClient restClient; //创建索引库 @Test public void testCreateIndex() throws IOException { //创建索引请求对象,并设置索引名称 CreateIndexRequest createIndexRequest = new CreateIndexRequest("es_learning"); //设置索引参数 createIndexRequest.settings(Settings.builder().put("number_of_shards",1) .put("number_of_replicas",0)); //设置映射 createIndexRequest.mapping("doc_type"," {\n" + " \t\"properties\": {\n" + " \"name\": {\n" + " \"type\": \"text\",\n" + " \"analyzer\":\"ik_max_word\",\n" + " \"search_analyzer\":\"ik_smart\"\n" + " },\n" + " \"description\": {\n" + " \"type\": \"text\",\n" + " \"analyzer\":\"ik_max_word\",\n" + " \"search_analyzer\":\"ik_smart\"\n" + " },\n" + " \"studymodel\": {\n" + " \"type\": \"keyword\"\n" + " },\n" + " \"price\": {\n" + " \"type\": \"float\"\n" + " }\n" + " }\n" + "}", XContentType.JSON); //创建索引操作客户端 IndicesClient indices = client.indices(); //创建响应对象 CreateIndexResponse createIndexResponse = indices.create(createIndexRequest); //得到响应结果 boolean acknowledged = createIndexResponse.isAcknowledged(); System.out.println(acknowledged); } //删除索引库 @Test public void testDeleteIndex() throws IOException { //删除索引请求对象 DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xc_course"); //删除索引 DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest); //删除索引响应结果 boolean acknowledged = deleteIndexResponse.isAcknowledged(); System.out.println(acknowledged); } }
//添加文档 @Test public void testAddDoc() throws IOException { //准备json数据 Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("name", "spring cloud"); jsonMap.put("description", "注册中心eureka。"); jsonMap.put("studymodel", "201001"); SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss"); jsonMap.put("timestamp", dateFormat.format(new Date())); jsonMap.put("price", 5.6f); //索引请求对象 IndexRequest indexRequest = new IndexRequest("es_learning","doc_type"); //指定索引文档内容 indexRequest.source(jsonMap); //索引响应对象 IndexResponse indexResponse = client.index(indexRequest); //获取响应结果 DocWriteResponse.Result result = indexResponse.getResult(); System.out.println(result); }
/查询文档
@Test
public void getDoc() throws IOException {
GetRequest getRequest = new GetRequest(
"es_learning",
"doc_type",
"mm6qWWsBNAqzzaUTFEOB");
GetResponse getResponse = client.get(getRequest);
boolean exists = getResponse.isExists();
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
System.out.println(sourceAsMap);
}
ES更新文档的顺序是:先检索到文档、将原来的文档标记为删除、创建新文档、删除旧文档,创建新文档就会重建索引。
//更新文档
@Test
public void updateDoc() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("es_learning", "doc_type",
"mm6qWWsBNAqzzaUTFEOB");
Map<String, String> map = new HashMap<>();
map.put("name", "spring cloud实战");
updateRequest.doc(map);
UpdateResponse update = client.update(updateRequest);
RestStatus status = update.status();
System.out.println(status);
}
//根据id删除文档
@Test
public void testDelDoc() throws IOException {
//删除文档id
String id = "mm6qWWsBNAqzzaUTFEOB";
//删除索引请求对象
DeleteRequest deleteRequest = new DeleteRequest("es_learning","doc",doc_type);
//响应对象
DeleteResponse deleteResponse = client.delete(deleteRequest);
//获取响应结果
DocWriteResponse.Result result = deleteResponse.getResult();
System.out.println(result);
}
7.1.1 创建映射
创建es_learning索引库。
创建如下映射
POST: http://localhost:9200/es_learning/doc_type/_mapping
{ "properties":{ "description":{ "type":"text", "analyzer":"ik_max_word", "search_analyzer":"ik_smart" }, "name":{ "type":"text", "analyzer":"ik_max_word", "search_analyzer":"ik_smart" }, "logo":{ "type":"text", "index":false }, "price":{ "type":"float" }, "studymodel":{ "type":"keyword" }, "timestamp":{ "type":"date", "format":"yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd||epoch_millis" } } }
http://localhost:9200/es_learning/doc_type/1 { "name": "Springboot", "description": "Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。", "studymodel": "201002", "price":38.6, "timestamp":"2019‐06‐15 14:11:35", "pic":"springboot.jpg" } http://localhost:9200/es_learning/doc_type/2 { "name": "spring基础", "description": "spring 在java领域非常流行,java程序员都在用。", "studymodel": "201001", "price":88.6, "timestamp":"2019‐06‐15 14:11:35", "pic":"spring.jpg" } http://localhost:9200/es_learning/doc_type/3 { "name": "elasticsearch", "description": "ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。", "studymodel": "201001", "price":99.9, "timestamp":"2019‐06‐15 14:11:35", "pic":"elasticsearch.png" }
简单搜索就是通过url进行查询,以get方式请求ES。
格式:get …/_search?q=…
q:搜索字符串。
?q=name:spring 搜索name中包括spring的文档。
DSL(Domain Specific Language)是ES提出的基于json的搜索方式,在搜索时传入特定的json格式的数据来完成不同的搜索需求。DSL比URI搜索方式功能强大,在项目中建议使用DSL方式来完成搜索。
查询所有索引库的文档。
GET http://localhost:9200/_search
查询指定索引库指定类型下的文档.
GET http://localhost:9200/es_learning/doc_type/_search
POST http://localhost:9200/es_learning/doc_type/_search
{
"query":{
"match_all":{
}
},
"_source":[
"name",
"studymodel"
]
}
_source:source源过虑设置,指定结果中所包括的字段有哪些。
@SpringBootTest @RunWith(SpringRunner.class) public class TestSearch { @Autowired RestHighLevelClient client; @Autowired RestClient restClient; //搜索type下的全部记录 @Test public void testSearchAll() throws IOException { SearchRequest searchRequest = new SearchRequest("es_learning"); searchRequest.types("doc_type"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()); //source源字段过虑 searchSourceBuilder.fetchSource(new String[]{"name","studymodel"}, new String[]{}); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); for (SearchHit hit : searchHits) { String index = hit.getIndex(); String type = hit.getType(); String id = hit.getId(); float score = hit.getScore(); String sourceAsString = hit.getSourceAsString(); Map<String, Object> sourceAsMap = hit.getSourceAsMap(); String name = (String) sourceAsMap.get("name"); String studymodel = (String) sourceAsMap.get("studymodel"); String description = (String) sourceAsMap.get("description"); System.out.println(name); System.out.println(studymodel); System.out.println(description); } } }
ES支持分页查询,传入两个参数:from和size。
form:表示起始文档的下标,从0开始。
size:查询的文档数量。
POST http://localhost:9200/es_learning/doc_type/_search
{
"from":0,
"size":1,
"query":{
"match_all":{
}
},
"_source":[
"name",
"studymodel"
]
}
SearchRequest searchRequest = new SearchRequest("es_learning");
searchRequest.types("doc_type");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//分页查询,设置起始下标,从0开始
searchSourceBuilder.from(0);
//每页显示个数
searchSourceBuilder.size(10);
//source源字段过虑
searchSourceBuilder.fetchSource(new String[]{"name","studymodel"}, new String[]{});
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);
Term Query为精确查询,在搜索时会整体匹配关键字,不再将关键字分词。
POST http://localhost:9200/es_learning/doc_type/_search
{
"query":{
"term":{
"name":"springboot"
}
},
"_source":[
"name",
"studymodel"
]
}
SearchRequest searchRequest = new SearchRequest("es_learning");
searchRequest.types("doc_type");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("name","springboot"));
//source源字段过虑
searchSourceBuilder.fetchSource(new String[]{"name","studymodel"}, new String[]{});
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);
ES提供根据多个id值匹配的方法:
POST http://localhost:9200/es_learning/doc_type/_search
{
"query":{
"ids":{
"type":"doc_type",
"values":["2","3","4"]
}
}
}
SearchRequest searchRequest = new SearchRequest("es_learning");
searchRequest.types("doc_type");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
String[] split = new String[]{"2","3","4"};
List<String> idList = Arrays.asList(split);
searchSourceBuilder.query(QueryBuilders.termsQuery("_id", idList));
1、基本使用
match Query即全文检索,它的搜索方式是先将搜索字符串分词,再使用各各词条从索引中搜索。
match query与Term query区别是match query在搜索前先将搜索关键字分词,再拿各各词语去索引中搜索。
POST http://localhost:9200/es_learning/doc_type/_search
{
"query":{
"match":{
"description":{
"query":"spring boot",
"operator":"or"
}
}
}
}
query:搜索的关键字,对于英文关键字如果有多个单词则中间要用半角逗号分隔,而对于中文关键字中间可以用逗号分隔也可以不用。
operator:or 表示 只要有一个词在文档中出现则就符合条件,and表示每个词都在文档中出现则才符合条件。
//根据关键字搜索 @Test public void testMatchQuery() throws IOException { SearchRequest searchRequest = new SearchRequest("es_learning"); searchRequest.types("doc_type"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //source源字段过虑 searchSourceBuilder.fetchSource(new String[]{"name","studymodel"}, new String[]{}); //匹配关键字 searchSourceBuilder.query(QueryBuilders.matchQuery("description", "spring boot").operator(Operator.OR)); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); for (SearchHit hit : searchHits) { String index = hit.getIndex(); String type = hit.getType(); String id = hit.getId(); float score = hit.getScore(); String sourceAsString = hit.getSourceAsString(); Map<String, Object> sourceAsMap = hit.getSourceAsMap(); String name = (String) sourceAsMap.get("name"); String studymodel = (String) sourceAsMap.get("studymodel"); String description = (String) sourceAsMap.get("description"); System.out.println(name); System.out.println(studymodel); System.out.println(description); } }
2、minimum_should_match
上边使用的operator = or表示只要有一个词匹配上就得分,如果实现三个词至少有两个词匹配如何实现?使用minimum_should_match可以指定文档匹配词的占比:
{
"query":{
"match":{
"description":{
"query":"spring框架",
"minimum_should_match":"80%"
}
}
}
}
设置"minimum_should_match": "80%"表示,三个词在文档的匹配占比为80%,即3*0.8=2.4,向下取整得2,表示至少有两个词在文档中要匹配成功。
SearchRequest searchRequest = new SearchRequest("es_learning");
searchRequest.types("doc_type");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//匹配关键字
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("description", "前台页面开发框架 架
构")
.minimumShouldMatch("80%");//设置匹配占比
searchSourceBuilder.query(matchQueryBuilder);
上边学习的termQuery和matchQuery一次只能匹配一个Field,本节学习multiQuery,一次可以匹配多个字段。
1、基本使用
单项匹配是在一个field中去匹配,多项匹配是拿关键字去多个Field中匹配。
{
"query":{
"multi_match":{
"query":"spring boot",
"minimum_should_match":"50%",
"fields":["name","description"]
}
}
}
2、提升boost
匹配多个字段时可以提升字段的 boost(权重)来提高得分
{
"query":{
"multi_match":{
"query":"spring boot",
"minimum_should_match":"50%",
"fields":["name^10","description"]
}
}
}
“name^10” 表示权重提升10倍,执行上边的查询。
MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring 框架",
"name", "description")
.minimumShouldMatch("50%");
multiMatchQueryBuilder.field("name",10);//提升boost
布尔查询对应于Lucene的BooleanQuery查询,实现将多个查询组合起来。
{ "_source":[ "name", "studymodel", "description" ], "from":0, "size":1, "query":{ "bool":{ "must":[ { "multi_match":{ "query":"spring框架", "minimum_should_match":"50%", "fields":[ "name^10", "description" ] } }, { "term":{ "studymodel":"201001" } } ] } } }
//BoolQuery ,将搜索关键字分词,拿分词去索引库搜索 @Test public void testBoolQuery() throws IOException { //创建搜索请求对象 SearchRequest searchRequest= new SearchRequest("es_learning"); searchRequest.types("doc_type"); //创建搜索源配置对象 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.fetchSource(new String[]{"name","pic","studymodel"},new String[]{}); //multiQuery String keyword = "spring开发框架"; MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring框架", "name", "description") .minimumShouldMatch("50%"); multiMatchQueryBuilder.field("name",10); //TermQuery TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("studymodel", "201001"); // 布尔查询 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(multiMatchQueryBuilder); boolQueryBuilder.must(termQueryBuilder); //设置布尔查询对象 searchSourceBuilder.query(boolQueryBuilder); searchRequest.source(searchSourceBuilder);//设置搜索源配置 SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); for(SearchHit hit:searchHits){ Map<String, Object> sourceAsMap = hit.getSourceAsMap(); System.out.println(sourceAsMap); } }
过虑是针对搜索的结果进行过虑,过虑器主要判断的是文档是否匹配,不去计算和判断文档的匹配度得分,所以过虑器性能比查询要高,且方便缓存,推荐尽量使用过虑器去实现查询或者过虑器和查询共同使用。过虑器在布尔查询中使用,下边是在搜索结果的基础上进行过虑:
{ "_source":[ "name", "studymodel", "description", "price" ], "query":{ "bool":{ "must":[ { "multi_match":{ "query":"spring框架", "minimum_should_match":"50%", "fields":[ "name^10", "description" ] } } ], "filter":[ { "term":{ "studymodel":"201001" } }, { "range":{ "price":{ "gte":60, "lte":100 } } } ] } } }
// 布尔查询使用过虑器 @Test public void testFilter() throws IOException { SearchRequest searchRequest = new SearchRequest("es_learning"); searchRequest.types("doc_type"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //source源字段过虑 searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","description"}, new String[]{}); searchRequest.source(searchSourceBuilder); //匹配关键字 MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring框 架", "name", "description"); //设置匹配占比 multiMatchQueryBuilder.minimumShouldMatch("50%"); //提升另个字段的Boost值 multiMatchQueryBuilder.field("name",10); searchSourceBuilder.query(multiMatchQueryBuilder); //布尔查询 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(searchSourceBuilder.query()); //过虑 boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel", "201001")); boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100)); SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); for (SearchHit hit : searchHits) { String index = hit.getIndex(); String type = hit.getType(); String id = hit.getId(); float score = hit.getScore(); String sourceAsString = hit.getSourceAsString(); Map<String, Object> sourceAsMap = hit.getSourceAsMap(); String name = (String) sourceAsMap.get("name"); String studymodel = (String) sourceAsMap.get("studymodel"); String description = (String) sourceAsMap.get("description"); System.out.println(name); System.out.println(studymodel); System.out.println(description); } }
可以在字段上添加一个或多个排序,支持在keyword、date、float等类型上添加,text类型的字段上不允许添加排序。
{ "_source":[ "name", "studymodel", "description", "price" ], "query":{ "bool":{ "filter":[ { "range":{ "price":{ "gte":0, "lte":100 } } } ] } }, "sort":[ { "studymodel":"desc" }, { "price":"asc" } ] }
@Test public void testSort() throws IOException { SearchRequest searchRequest = new SearchRequest("es_learning"); searchRequest.types("doc_type"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //source源字段过虑 searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","description"}, new String[]{}); searchRequest.source(searchSourceBuilder); //布尔查询 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //过虑 boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100)); // 排序 searchSourceBuilder.sort(new FieldSortBuilder("studymodel").order(SortOrder.DESC)); searchSourceBuilder.sort(new FieldSortBuilder("price").order(SortOrder.ASC)); SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); for (SearchHit hit : searchHits) { String index = hit.getIndex(); String type = hit.getType(); String id = hit.getId(); float score = hit.getScore(); String sourceAsString = hit.getSourceAsString(); Map<String, Object> sourceAsMap = hit.getSourceAsMap(); String name = (String) sourceAsMap.get("name"); String studymodel = (String) sourceAsMap.get("studymodel"); String description = (String) sourceAsMap.get("description"); System.out.println(name); System.out.println(studymodel); System.out.println(description); } }
高亮显示可以将搜索结果一个或多个字突出显示,以便向用户展示匹配关键字的位置。在搜索语句中添加highlight即可实现。
{ "_source":[ "name", "studymodel", "description", "price" ], "query":{ "bool":{ "filter":[ { "range":{ "price":{ "gte":0, "lte":100 } } } ] } }, "sort":[ { "studymodel":"desc" }, { "price":"asc" } ], "highlight":{ "pre_tags":[ "<tag1>" ], "post_tags":[ "</tag2>" ], "fields":{ "name":{ }, "description":{ } } } }
@Test public void testHighlight() throws IOException { SearchRequest searchRequest = new SearchRequest("xc_course"); searchRequest.types("doc"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //source源字段过虑 searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","description"}, new String[]{}); searchRequest.source(searchSourceBuilder); //匹配关键字 MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("开发", "name", "description"); searchSourceBuilder.query(multiMatchQueryBuilder); //布尔查询 BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(searchSourceBuilder.query()); //过虑 boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100)); //排序 searchSourceBuilder.sort(new FieldSortBuilder("studymodel").order(SortOrder.DESC)); searchSourceBuilder.sort(new FieldSortBuilder("price").order(SortOrder.ASC)); //高亮设置 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.preTags("<tag>");//设置前缀 highlightBuilder.postTags("</tag>");//设置后缀 // 设置高亮字段 highlightBuilder.fields().add(new HighlightBuilder.Field("name")); searchSourceBuilder.highlighter(highlightBuilder); SearchResponse searchResponse = client.search(searchRequest); SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); for (SearchHit hit : searchHits) { Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //名称 String name = (String) sourceAsMap.get("name"); //取出高亮字段内容 Map<String, HighlightField> highlightFields = hit.getHighlightFields(); if(highlightFields!=null){ HighlightField nameField = highlightFields.get("name"); if(nameField!=null){ Text[] fragments = nameField.getFragments(); StringBuffer stringBuffer = new StringBuffer(); for (Text str : fragments) { stringBuffer.append(str.string()); } name = stringBuffer.toString(); } } String index = hit.getIndex(); String type = hit.getType(); String id = hit.getId(); float score = hit.getScore(); String sourceAsString = hit.getSourceAsString(); String studymodel = (String) sourceAsMap.get("studymodel"); String description = (String) sourceAsMap.get("description"); System.out.println(name); System.out.println(studymodel); System.out.println(description); } }
ES通常以集群方式工作,这样做不仅能够提高 ES的搜索能力还可以处理大数据搜索的能力,同时也增加了系统的容错能力及高可用,ES可以实现PB级数据的搜索。
从上图总结以下概念:
下边的例子实现创建一个2结点的集群,并且索引的分片我们设置2片,每片一个副本。
解压elasticsearch-6.2.4.zip ,结点1对外服务的http端口是:9200 ;集群管理端口是9300;结点名:es_node_1,elasticsearch.yml内容如下
cluster.name: es-cluster
node.name: es_node_1
network.host: 0.0.0.0
http.port: 9200
transport.tcp.port: 9300
node.master: true
node.data: true
discovery.zen.ping.unicast.hosts: ["0.0.0.0:9300", "0.0.0.0:9301"]
discovery.zen.minimum_master_nodes: 1
node.ingest: true
node.max_local_storage_nodes: 2
path.data: D:\ElasticSearch\elasticsearch‐6.2.1‐1\data
path.logs: D:\ElasticSearch\elasticsearch‐6.2.1‐1\logs
http.cors.enabled: true
http.cors.allow‐origin: /.*/
解压elasticsearch-6.2.4.zip ,结点1对外服务的http端口是:9202 ;集群管理端口是9302;结点名:es_node_2,elasticsearch.yml内容如下
cluster.name: es-cluster
node.name: es_node_2
network.host: 0.0.0.0
http.port: 9202
transport.tcp.port: 9302
node.master: true
node.data: true
discovery.zen.ping.unicast.hosts: ["0.0.0.0:9300", "0.0.0.0:9301"]
discovery.zen.minimum_master_nodes: 1
node.ingest: true
node.max_local_storage_nodes: 2
path.data: D:\ElasticSearch\elasticsearch‐6.2.1‐1\data
path.logs: D:\ElasticSearch\elasticsearch‐6.2.1‐1\logs
http.cors.enabled: true
http.cors.allow‐origin: /.*/
为每个结点安装IK分词器,并启动,然后创建索引库并设置分片数。
在一个节点上创建文档,发现在其他节点上也可以查询到数据,还可进行节点的增删测试。
通过访问 GET /_cluster/health 来查看Elasticsearch 的集群健康情况。
用三种颜色来展示健康状态:green:所有的主分片和副本分片都正常运行; yellow:所有的主分片都正常运行,但有些副本分片运行不正常;red:存在主分片运行不正常。
Get请求:http://localhost:9200/_cluster/health
{ "cluster_name": "es-cluster", "status": "green", "timed_out": false, "number_of_nodes": 2, "number_of_data_nodes": 2, "active_primary_shards": 2, "active_shards": 4, "relocating_shards": 0, "initializing_shards": 0, "unassigned_shards": 0, "delayed_unassigned_shards": 0, "number_of_pending_tasks": 0, "number_of_in_flight_fetch": 0, "task_max_waiting_in_queue_millis": 0, "active_shards_percent_as_number": 100 }
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。