1. 初始es
- 解压

解压后的工程目录,data文件夹不存在可以手动创建
- elasticsearch-analysis-ik-6.2.1.zip 解压后的文件复制到 es -> plugins中 并重命名为ik (ik分词器)

- elasticsearch-head.7z 解压,es的ui
- 修改配置文件
- elasticsearch.yml : 用于配置Elasticsearch运行参数
- jvm.options : 用于配置Elasticsearch JVM设置
- log4j2.properties: 用于配置Elasticsearch日志

- elasticsearch.yml ```yaml cluster.name: lixin node.name: lx_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 bootstrap.memory_lock: false node.max_local_storage_nodes: 2
path.data: 当前es存放data的目录 path.logs: 当前es存放logs的目录
http.cors.enabled: true http.cors.allow-origin: /.*/
```cluster.name: 配置elasticsearch的集群名称,默认是elasticsearch。建议修改成一个有意义的名称。方便管理一个或多个节点组成一个cluster集群,集群是一个逻辑的概念,节点是物理概念,后边章节会详细介绍。path.conf: 设置配置文件的存储路径,tar或zip包安装默认在es根目录下的confifig文件夹,rpm安装默认在/etc/elasticsearch path.data: 设置索引数据的存储路径,默认是es根目录下的data文件夹,可以设置多个存储路径,用逗号隔开。path.logs: 设置日志文件的存储路径,默认是es根目录下的logs文件夹path.plugins: 设置插件的存放路径,默认是es根目录下的plugins文件夹bootstrap.memory_lock: true 设置为true可以锁住ES使用的内存,避免内存与swap分区交换数据。network.host: 设置绑定主机的ip地址,设置为0.0.0.0表示绑定任何ip,允许外网访问,生产环境建议设置为具体 的ip。http.port: 9200设置对外服务的http端口,默认为9200。transport.tcp.port: 9300 集群结点之间通信端口node.master: 指定该节点是否有资格被选举成为master结点,默认是true,如果原来的master宕机会重新选举新的master。node.data: 指定该节点是否存储索引数据,默认为true。discovery.zen.ping.unicast.hosts: ["host1:port", "host2:port", "..."] 设置集群中master节点的初始列表。discovery.zen.ping.timeout: 3s 设置ES自动发现节点连接超时的时间,默认为3秒,如果网络延迟高可设置大些。discovery.zen.minimum_master_nodes: 主结点数量的最少值 ,此值的公式为:(master_eligible_nodes / 2) + 1 ,比如:有3个符合要求的主结点,那么这 里要设置为2。node.max_local_storage_nodes: 单机允许的最大存储结点数,通常单机启动一个结点建议设置为1,开发环境如果单机启动多个节点可设置大于1.
- jvm.options
设置最小及最大的JVM堆内存大小:在jvm.options中设置 -Xms和-Xmx:1) 两个值设置为相等2) 将 Xmx 设置为不超过物理内存的一半。
2. 启动es
- 双击启动

访问服务 http://localhost:9200,出现如下安装成功
3. es ui(可以不装)
启动ui 进入解压后的路径,cmd,执行npm install 命令

- 安装完成后会出现node_modules -> 执行npm run start,启动服务

4. Java 实现 ES
引入jar包
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>6.2.1</version></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>6.2.1</version></dependency>
配置文件
server:port: 31002spring:application:name: xc-servie-searchlixin:elasticsearch:hostList: ${eshoplist:127.0.0.1} #多个节点用逗号分割
配置类 ```java package com.lixin.search.config;
import lombok.extern.slf4j.Slf4j; 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;
/**
- elasticsearch *
- @author li-xin
@since 2022-02-06 13:02:51 */ @Slf4j @Configuration public class ElasticsearchConfig {
@Value(“${lixin.elasticsearch.hostList}”) private String hostList;
@Bean public RestHighLevelClient restHighLevelClient() {
HttpHost[] httpHosts = httpHostsCreate();return new RestHighLevelClient(RestClient.builder(httpHosts));
}
//项目主要使用RestHighLevelClient,对于低级的客户端暂时不用 @Bean public RestClient restClient() {
HttpHost[] httpHosts = httpHostsCreate();return RestClient.builder(httpHosts).build();
}
/**
- 将 hostList封装为httpHost数组
*/
private HttpHost[] httpHostsCreate() {
// yml参数切割
String[] hosts = hostList.split(“,”);
// 封装参数
HttpHost[] httpHosts = new HttpHost[hosts.length];
for (int i = 0; i < hosts.length; i++) {
} return httpHosts; } } ```String host = hosts[i];String[] httpHostArray = host.split(":");int httpHostPort = 9200;try {if(httpHostArray.length > 1){httpHostPort = Integer.parseInt(httpHostArray[1]);}} catch (NumberFormatException e) {log.error("创建httpHost获取端口异常:{}, 端口为:{}", httpHostArray, httpHostPort);}httpHosts[i] = new HttpHost(host.split(":")[0], httpHostPort, "http");
- 构建测试类 ```java package com.lixin.search;
import org.elasticsearch.client.RestHighLevelClient; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;
/**
- elasticsearch test java - 功能 *
- @author li-xin
@since 2022-02-07 15:10:54 */ @SpringBootTest public class TestDemo {
@Autowired private RestHighLevelClient restHighLevelClient; } ```
4.1 索引库 - 创建 /删除 *
创建空索引库 - (类似空表)
PUT http://localhost:9200/lixin
{"settings": {"index": {"number_of_shards": "1","number_of_replicas": "0"}}}
添加索引库属性 - (类似表中添加字段)
POST http://localhost:9200/lixin/doc/_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"}}}
4.1.1 创建 - 索引库并构建结构 *
/*** 创建 - 索引库并构建结构*/@Testpublic void createIndex() throws IOException {CreateIndexRequest createIndexRequest = new CreateIndexRequest("lixin");createIndexRequest.settings(Settings.builder().put("number_of_shards", "1").put("number_of_replicas", "0"));createIndexRequest.mapping("doc", "{\n" +" \"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" +" \"timestamp\": {\n" +" \"type\": \"date\",\n" +" \"format\": \"yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd||epoch_millis\"\n" +" }\n" +" }\n" +"}", XContentType.JSON);restHighLevelClient.indices().create(createIndexRequest);}
4.1.2 删除 - 索引库 *
/*** 删除 - 索引库*/@Testpublic void deleteIndex() throws IOException {DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("lixin");try {DeleteIndexResponse deleteIndexResponse = restHighLevelClient.indices().delete(deleteIndexRequest);boolean acknowledged = deleteIndexResponse.isAcknowledged();if(acknowledged){System.out.println("删除成功");}} catch (ElasticsearchStatusException e) {System.out.println("删除失败/已被删除");}}
4.2 索引库 - 添加记录
索引表中添加内容 - (类似表中添加数据)
POST http://localhost:9200/lixin/doc/3
{"name": "spring开发基础","description": "spring 在java领域非常流行,java程序员都在用。","studymodel": "201001","price": 88.6,"timestamp": "2018‐02‐24 19:11:35","pic": "group1/M00/00/00/wKhlQFs6RCeAY0pHAAJx5ZjNDEM428.jpg"}
4.2.1 索引库 - 添加内容 *
/*** 添加内容*/@Testpublic void addDocumentation() throws IOException {// 准备json数据Map<String, Object> jsonMap = new HashMap<>();jsonMap.put("name", "spring cloud实战");jsonMap.put("description", "本课程主要从四个章节进行讲解: 1.微服务架构入门 2.spring cloud 基础入门 3.实战Spring Boot 4.注册中心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("lixin", "doc");indexRequest.source(jsonMap);IndexResponse indexResponse = restHighLevelClient.index(indexRequest);DocWriteResponse.Result result = indexResponse.getResult();System.out.println(result);}// CREATED : 创建数据成功

4.2.2 索引库 - 查询内容
/*** 查询 - 内容*/@Testpublic void queryDocumentation() throws IOException{// 索引库,类型(新版本弱化此概念),idGetRequest getRequest = new GetRequest("lixin", "doc", "Qhpn034BCxymaSCrrRJS");GetResponse getResponse = restHighLevelClient.get(getRequest);boolean exists = getResponse.isExists();if(exists){Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();System.out.println(sourceAsMap);}}
4.2.3 索引库 - 更新内容
全局更新
POST http://localhost:9200/lixin/doc/Qhpn034BCxymaSCrrRJS
{"price": 9.6,"studymodel": 201001,"name": "spring cloud运行","description": "本课程主要从四个章节进行讲解: 1.微服务架构入门 2.spring cloud 基础入门 3.实战Spring Boot 4.注册中心eureka.","timestamp": "2018‐02‐24 19:11:35"}
局部更新
POST http://localhost:9200/lixin/doc/Qhpn034BCxymaSCrrRJS/_update
{"doc": {"price": 9.62}}
java 代码选用局部更新方式
/*** 更新 - 内容*/@Testpublic void updateDocumentation() throws IOException{UpdateRequest updateRequest = new UpdateRequest("lixin", "doc", "Qhpn034BCxymaSCrrRJS");updateRequest.doc("{\n" +" \"doc\": {\n" +" \"price\": 7.62\n" +" }\n" +"}", XContentType.JSON);UpdateResponse updateResponse = restHighLevelClient.update(updateRequest);RestStatus status = updateResponse.status();System.out.println(status);}
4.2.4 索引库 - 删除内容
通过id删除
java 代码 实现
/*** 删除 - 内容*/@Testpublic void deleteDocumentation() throws IOException{DeleteRequest deleteRequest = new DeleteRequest("lixin", "doc", "Qhpn034BCxymaSCrrRJS");DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest);DocWriteResponse.Result result = deleteResponse.getResult();System.out.println(result);}
4.3 ik 分词器
https://github.com/medcl/elasticsearch-analysis-ik/releases
POST http://localhost:9200/_analyze
{"text": "测试分词器,后边是测试内容:spring cloud实战","analyzer": "ik_max_word" // 不适用ik分词器去掉 这一段即可}
【注】: ik分词器中模式分为 ik_max_word和ik_smart 其中ik_smart 粒度较粗的分词
- 自定以分词 (自行配置词典)
iK分词器自带一个main.dic的文件,此文件为词库文件,同目录创建自定义文件my.dic,保存类型如果可以配置(注意文件格式为utf-8(不要选择utf-8 BOM)
IKAnalyzer.cfg.xml -> 文件中添加自定义路径
4.4 常见映射类型
6.2核心类型
String:text,keyword
Number:long,integer,short,byte,double,float,half_float,scaled_float
Date:date
Boolean:boolean
Binary:binary
Range:integer_range,float_range,long_range,double_range,date_range
- 字符串
text + keyword
analyzer是指在索引和搜索都使用ik_max_word,如果单独想定义搜索时使用的分词器则可以通过search_analyzer属性
{"name": {"type": "text","analyzer": "ik_max_word","search_analyzer": "ik_smart"}}
- index
默认为index=true,即要进行索引,只有进行索引才可以从索引库搜索到。但是也有一些内容不需要索引,比如:商品图片地址只被用来展示图片,不进行搜索图片,此时可以将index设置为false。删除索引,重新创建映射,将pic的index设置为false,尝试根据pic去搜索,结果搜索不到数据
{"pic": {"type": "text","index": false}}
- store
是否在source之外存储,每个文档索引后会在 ES中保存一份原始文档,存放在”_source”中,一般情况下不需要设置store为true,因为在_source中已经有一份原始文档了。
- date日期
日期类型不用设置分词器。通常日期类型的字段用于排序。下边的设置允许date字段存储年月日时分秒、年月日及毫秒三种格式。
{"properties": {"timestamp": {"type": "date","format": "yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd"}}}
4.5 搜索 测试数据 *
添加如下操作如果报错请确保索引库是否已存在,存在删除重新创建,不存在创建即可(参考4.1的1)
添加索引库属性 - (类似表中添加字段)
POST http://localhost:9200/lixin/doc/_mapping
{"properties": {"description": {"type": "text","analyzer": "ik_max_word","search_analyzer": "ik_smart"},"name": {"type": "text","analyzer": "ik_max_word","search_analyzer": "ik_smart"},"pic": {"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"}}}
- 索引表中添加内容 - (类似表中添加数据)
POST http://localhost:9200/lixin/doc/1
POST http://localhost:9200/lixin/doc/2{"name": "Bootstrap开发","description": "Bootstrap是由Twitter推出的一个前台页面开发框架,是一个非常流行的开发框架,此框架集成了 多种页面效果。此开发框架包含了大量的CSS、JS程序代码,可以帮助开发者(尤其是不擅长页面开发的程序人员)轻松 的实现一个不受浏览器限制的精美界面效果。","studymodel": "201002","price": 38.6,"timestamp": "2018‐04‐25 19:11:35","pic": "group1/M00/00/00/wKhlQFs6RCeAY0pHAAJx5ZjNDEM428.jpg"}
POST http://localhost:9200/lixin/doc/3{"name": "java编程基础","description": "java语言是世界第一编程语言,在软件开发领域使用人数最多。","studymodel": "201001","price": 68.6,"timestamp": "2018‐03‐25 19:11:35","pic": "group1/M00/00/00/wKhlQFs6RCeAY0pHAAJx5ZjNDEM428.jpg"}
{"name": "spring开发基础","description": "spring 在java领域非常流行,java程序员都在用。","studymodel": "201001","price": 88.6,"timestamp": "2018‐02‐24 19:11:35","pic": "group1/M00/00/00/wKhlQFs6RCeAY0pHAAJx5ZjNDEM428.jpg"}
4.6 索引库 - DSL搜索 *
POST http://localhost:9200/lixin/doc/_search
(以下postman方式的请求路径都一样)
4.6.1 获取结果集公共方法
private static final String index = "lixin";private static final String type = "doc";// 构建搜索请求private final SearchRequest searchRequest;{searchRequest = new SearchRequest(index);searchRequest.types(type);}/*** 获取结果集*/private void queryList(SearchRequest searchRequest) throws IOException {SearchResponse search = restHighLevelClient.search(searchRequest);// 结果SearchHits hits = search.getHits();// 总数long totalHits = hits.getTotalHits();System.out.println(totalHits);for (SearchHit hit : hits) {String type = hit.getType();String index = hit.getIndex();String id = hit.getId();float score = hit.getScore();String sourceAsString = hit.getSourceAsString();// 记录内容mapMap<String, Object> sourceAsMap = hit.getSourceAsMap();// 高亮Map<String, HighlightField> highlightFields = hit.getHighlightFields();if (!highlightFields.isEmpty()) {HighlightField name = highlightFields.get("name");if (name != null) {String name1 = name.getName();System.out.println("name:" + name1);String s = Arrays.toString(name.getFragments());System.out.println("nameStr:" + s);}}String name = (String) sourceAsMap.get("name");String studymodel = (String) sourceAsMap.get("studymodel");String description = (String) sourceAsMap.get("description");System.out.println(index + ".." + type + ".." + id + ".." + score);System.out.println(sourceAsString);System.out.println(name);System.out.println(studymodel);System.out.println(description);System.out.println("===========================");}}
4.6.2 全查询
{"query": {"match_all": {}},"_source": ["name","studymodel","description"]}
/*** 搜索 - 全匹配*/@Testpublic void searchMatchAll() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();// 全匹配searchSourceBuilder.query(QueryBuilders.matchAllQuery());// 展示的字段 1.string[]表示展示字段 2.string[]表示不显示字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel","description"}, new String[]{});searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.3 分页查询
{"from": 0,"size": 1,"query": {"match_all": {}},"_source": ["name","studymodel"]}
/*** 搜索 - 分页*/@Testpublic void searchPageSize() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();int page = 2;int size = 1;int from = (page - 1) * size;// 分页即可searchSourceBuilder.from(from);searchSourceBuilder.size(size);searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.4 term精确查询
Term Query为精确查询,在搜索时会整体匹配关键字,不再将关键字分词
{"query": {"term": {"name":"spring开发"}},"_source": ["name","studymodel"]}
/*** 搜索 - term精确查询*/@Testpublic void searchTerm() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();searchSourceBuilder.query(QueryBuilders.termQuery("name", "开发"));// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.5 通过ids精确查询
{"query": {"ids": {"type": "doc","values": ["3","100","2"]}}}
/*** 搜索 - ids*/@Testpublic void searchIds() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();List<String> ids = Arrays.asList("3", "100", "2");// 【注意】使用的termssearchSourceBuilder.query(QueryBuilders.termsQuery("_id", ids));// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.6 match全文检索
match Query即全文检索,它的搜索方式是先将搜索字符串 分词,再使用各各词条从索引中搜索。
match query与Term query区别是match query在搜索前先将搜索关键字分词,再拿各各词语去索引中搜索。
query:搜索的关键字,对于英文关键字如果有多个单词则中间要用半角逗号分隔,而对于中文关键字中间可以用逗号分隔也可以不用。
operator:or 表示 只要有一个词在文档中出现则就符合条件,and表示每个词都在文档中出现则才符合条件。
{"query": {"match": {"description": {"query": "spring java","operator": "and"}}}}
java 代码省略,可参考4.6.7代码
4.6.7 match百分比
operator = or表示只要有一个词匹配上就得分,如果实现三个词至少有两个词匹配使用minimum_should_match可以指定文档匹配词的占比,设置”minimum_should_match”: “80%”表示,三个词在文档的匹配占比为80%,即3*0.8=2.4,向上取整得2,表示至少有两个词在文档中要匹配成功。
{"query": {"match": {"description": {"query": "spring开发框架","minimum_should_match": "80%"}}}}
/*** 搜索 - match百分比*/@Testpublic void searchMatch() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();searchSourceBuilder.query(QueryBuilders.matchQuery("description", "spring开发框架").minimumShouldMatch("80%"));// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.8 multi 多字段权重
提升boost匹配多个字段时可以提升字段的boost(权重)来提高得分,”name^10” 表示权重提升10倍,执行上边的查询,发现name中包括java关键字的文档排在前边。
{"query": {"multi_match": {"query": "java","minimum_should_match": "50%","fields": ["name^10","description"]}}}
/*** 搜索 - match百分比 - 多字段*/@Testpublic void searchMatchMul() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();searchSourceBuilder.query(QueryBuilders.multiMatchQuery("java", "name", "description").minimumShouldMatch("80%").field("description", 10));// 权重// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.9 bool:权重+term
must:文档必须匹配must所包括的查询条件,相当于 “AND”
should:文档应该匹配should所包括的查询条件其中的一个或多个,相当于 “OR”
must_not:文档不能匹配must_not所包括的该查询条件,相当于”NOT”
- must:表示必须,多个查询条件必须都满足。(通常使用must)
- should:表示或者,多个查询条件只要有一个满足即可。
must_not:表示非。
{"_source": ["name","description","studymodel"],"from": 0,"size": 1,"query": {"bool": {"must": [{"multi_match": {"query": "java","minimum_should_match": "50%","fields": ["name^10","description"]}},{"term": {"studymodel": "201001"}}]}}}
/*** bool:权重 + term*/@Testpublic void boolTermQuery() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();// 权重MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("java", "name", "description").minimumShouldMatch("80%").field("description", 10);// 精确查询TermQueryBuilder termQuery = QueryBuilders.termQuery("studymodel", "201001");// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});// boolBoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();boolQueryBuilder.must(multiMatchQueryBuilder);boolQueryBuilder.must(termQuery);// sourcesearchSourceBuilder.query(boolQueryBuilder);searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.10 bool:权重+filter
过滤是针对搜索的结果进行过滤,过滤器主要判断的是文档是否匹配,不去计算和判断文档的匹配度得分,所以过滤器性能比查询要高,且方便缓存,推荐尽量使用过滤器去实现查询或者过滤器和查询共同使用。
{"_source": ["name","description","studymodel"],"query": {"bool": {"must": [{"multi_match": {"query": "java","minimum_should_match": "50%","fields": ["name^10","description"]}}],"filter": [{"term": {"studymodel": "201001"}},{"range": {"price": {"gte": 80,"lte": 100}}}]}}}
/*** bool:权重 + filter*/@Testpublic void boolFilterQuery() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();// 权重MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("java", "name", "description").minimumShouldMatch("80%").field("description", 10);// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});// boolBoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();boolQueryBuilder.must(multiMatchQueryBuilder);// 过滤boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel", "201001"));boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(80).lte(100));// sourcesearchSourceBuilder.query(boolQueryBuilder);searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.11 bool:排序
可以在字段上添加一个或多个排序,支持在keyword、date、float等类型上添加,text类型的字段上不允许添加排序。
{"_source": ["name","description","studymodel"],"query": {"bool": {"filter": [{"range": {"price": {"gte": 60,"lte": 100}}}]}},"sort": [{"studymodel": "desc"},{"price": "asc"}]}
/*** 排序*/@Testpublic void sortQuery() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});// boolBoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();// 过滤boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));// sourcesearchSourceBuilder.query(boolQueryBuilder);// 排序searchSourceBuilder.sort("studymodel", SortOrder.DESC);searchSourceBuilder.sort("price", SortOrder.ASC);searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
4.6.12 bool:高亮
高亮显示可以将搜索结果一个或多个字突出显示,以便向用户展示匹配关键字的位置。
{"_source": ["name","description","studymodel"],"query": {"bool": {"must": [{"multi_match": {"query": "开发框架","minimum_should_match": "50%","fields": ["name^10","description"]}}],"filter": [{"range": {"price": {"gte": 60,"lte": 100}}}]}},"sort": [{"price": "asc"}],"highlight": {"pre_tags": ["<tag>"],"post_tags": ["</tag>"],"fields": {"name": {},"description": {}}}}
/*** 高亮*/@Testpublic void highLightQuery() throws IOException {SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("开发框架", "description", "name").minimumShouldMatch("50%").field("name", 10);// 展示的字段searchSourceBuilder.fetchSource(new String[]{"name", "studymodel", "description"}, new String[]{});// boolBoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();boolQueryBuilder.must(multiMatchQueryBuilder);// 过滤boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(60).lte(100));// sourcesearchSourceBuilder.query(boolQueryBuilder);// 排序searchSourceBuilder.sort("price", SortOrder.ASC);// 高亮HighlightBuilder highlightBuilder = new HighlightBuilder();highlightBuilder.preTags("<tag>");highlightBuilder.postTags("</tag>");highlightBuilder.fields().add(new HighlightBuilder.Field("name"));highlightBuilder.fields().add(new HighlightBuilder.Field("description"));searchSourceBuilder.highlighter(highlightBuilder);searchRequest.source(searchSourceBuilder);// 获取结果集queryList(searchRequest);}
