环境搭建
1、建项目:elasticsearch_Java888
2、改pom
引入依赖:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.8.0</version>
</dependency>
完整版:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>elasticsearch_Java888</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.3.7.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.18.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.4.1</version>
</dependency>
<!--ElasticSearch Java 客户端依赖-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.8.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>6.8.0</version>
</dependency>
<!--json格式转化-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
</project>
3、建测试类
快捷键:ctrl + shift + t
索引相关操作
开始我们使用 kibana 客户端进行ES的操作
类比Kibana客户端的方式创建以下数据:
# 创建索引/类型、映射
# name 和 content 属性使用IK进行分词
PUT /ems
{
"mappings":{
"emp":{
"properties":{
"name":{
"type":"text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"age":{
"type":"integer"
},
"bir":{
"type":"date"
},
"content":{
"type":"text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_max_word"
},
"address":{
"type":"keyword"
}
}
}
}
}
# 索引文档
PUT /ems/emp/_bulk
{"index":{}}
{"name":"小黑","age":23,"bir":"2012-12-12","content":"为开发团队选择一款优秀的MVC框架是件难事儿,在众多可行的方案中决择需要很高的经验和水平","address":"北京"}
{"index":{}}
{"name":"王小黑","age":24,"bir":"2012-12-12","content":"Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式","address":"上海"}
{"index":{}}
{"name":"张小五","age":8,"bir":"2012-12-12","content":"Spring Cloud 作为Java 语言的微服务框架,它依赖于Spring Boot,有快速开发、持续交付和容易部署等特点。Spring Cloud 的组件非常多,涉及微服务的方方面面,井在开源社区Spring 和Netflix 、Pivotal 两大公司的推动下越来越完善","address":"无锡"}
{"index":{}}
{"name":"win7","age":9,"bir":"2012-12-12","content":"Spring的目标是致力于全方位的简化Java开发。 这势必引出更多的解释, Spring是如何简化Java开发的?","address":"南京"}
{"index":{}}
{"name":"梅超风","age":43,"bir":"2012-12-12","content":"Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API","address":"杭州"}
{"index":{}}
{"name":"张无忌","age":59,"bir":"2012-12-12","content":"ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口","address":"北京"}
创建 ES 客户端
//创建 ES 客户端操作对象
@Test
public void testJavaClient() throws UnknownHostException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
// Kibanan连接ES的端口为9200,Java 连接ES的方式为TCP,所以使用的端口为9300
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"),9300));
//ES相关操作
//关闭连接
transportClient.close();
}
开启测试,如果没有报错,就代表我们的连接成功!
创建索引
@Test
public void testIndex() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"),9300));
//创建索引:需要一个CreateIndexRequest 请求
CreateIndexRequest indexRequest = new CreateIndexRequest("ems");
CreateIndexResponse response = transportClient.admin().indices().create(indexRequest).get();
System.out.println(response.isAcknowledged());//查看创建结果
//关闭连接
transportClient.close();
}
创建索引/类型/映射
我们在kibana中定义索引/类型/映射,而这里索引和类型都通过api实现了,只需要我们定义映射,即
properties部分,要注意这里映射的格式必须是json格式,同时如果你从上面给的数据进行复制的话,还需要对其进行压缩。
@Test
public void testIndexAndType() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"),9300));
//创建索引
CreateIndexRequest indexRequest = new CreateIndexRequest("ems");
//定义json格式的映射
String mappingJson = "{\"properties\":{\"name\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"},\"age\":{\"type\":\"integer\"},\"sex\":{\"type\":\"keyword\"},\"content\":{\"type\":\"text\",\"analyzer\":\"ik_max_word\"}}}";
indexRequest.mapping("emp",mappingJson, XContentType.JSON);
//创建类型和映射
CreateIndexResponse response = transportClient.admin().indices().create(indexRequest).get();
System.out.println(response.isAcknowledged());//查看创建结果
//关闭连接
transportClient.close();
}
删除索引
@Test
public void testDeleteIndex() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"),9300));
//删除索引:需要一个DeleteIndexRequest请求
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("ems");
AcknowledgedResponse response = transportClient.admin().indices().delete(deleteIndexRequest).get();
System.out.println(response.isAcknowledged());
//关闭连接
transportClient.close();
}
索引一条记录
指定id索引记录
在kibana中我们索引文档时,可以指定id,也可以随机生成
@Test
public void testIndexDocument() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//指定id索引一条记录
Emp emp = new Emp("1", "小肥羊", 18, new Date(), "小肥羊是一只单纯的羊,他很单纯!", "北京");
String s = JSONObject.toJSONString(emp);
IndexResponse indexResponse = transportClient.prepareIndex("ems", "emp", emp.getId()).setSource(s, XContentType.JSON).get();
System.out.println(indexResponse.status());
//关闭连接
transportClient.close();
}
注意: 索引文档时,需要json格式
自定生成id索引记录
prepareIndex 时不传入第三个参数即可,ES会随机生成一个id
@Test
public void testIndexDocument() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//指定id索引一条记录
Emp emp = new Emp(null, "棒棒娃", 20, new Date(), "棒棒娃是一只努力的人,他很努力!", "重庆");
String s = JSONObject.toJSONString(emp);
IndexResponse indexResponse = transportClient.prepareIndex("ems", "emp").setSource(s, XContentType.JSON).get();
System.out.println(indexResponse.status());
//关闭连接
transportClient.close();
}
更新一条索引
我们需要保持原有文档数据不变,在此基础上进行更新
@Test
public void testUpdateDocument() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//更新文档
Emp emp = new Emp();
emp.setContent("帮帮娃今天去四川了!");
String s = JSONObject.toJSONString(emp);
UpdateResponse updateResponse = transportClient.prepareUpdate("ems","emp","1").setDoc(s,XContentType.JSON).get();
System.out.println(updateResponse.status());
//关闭连接
transportClient.close();
}
setDoc 表示原有数据文档不变
删除一条索引
传入我们所需要删除文档的id即可
@Test
public void testDeleteDocument() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//删除文档
DeleteResponse deleteResponse = transportClient.prepareDelete("ems", "emp", "QqCqr3YBWFsguNUCcwL1").get();
System.out.println(deleteResponse.status());
//关闭连接
transportClient.close();
}
批量操作
@Test
public void testBulkDocument() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//批量处理
//1.添加文档
IndexRequest indexRequest = new IndexRequest("ems","emp","3");
Emp emp = new Emp("2", "小飞", 30, new Date(), "小飞飞往太空", "太空");
String s = JSONObject.toJSONString(emp);
indexRequest.source(s, XContentType.JSON);
//2.更新文档
UpdateRequest updateRequest = new UpdateRequest("ems","emp","1");
Emp emp1 = new Emp();
emp1.setName("中国军人");
String s1 = JSONObject.toJSONString(emp1);
updateRequest.doc(s, XContentType.JSON);
//3.删除文档
DeleteRequest deleteRequest = new DeleteRequest("ems", "emp", "1");
//将需要执行的操作加入构建的bulk中:add可以添加多个
BulkResponse itemResponses = transportClient.prepareBulk()
.add(indexRequest)
.add(updateRequest)
.add(deleteRequest)
.get();
//ES批量操作不支持原子性:可以成功,可以失败
BulkItemResponse[] items = itemResponses.getItems();
for (BulkItemResponse b : items) {
System.out.println(b.status());
}
//关闭连接
transportClient.close();
}
检索
1. 查询所有并排序
查询所有并排序
- ASC 升序 DESC 降序
- addSort(“age”, SortOrder.ASC) 指定排序字段以及使用哪种方式排序
- addSort(“age”, SortOrder.DESC) 指定排序字段以及使用哪种方式排序
打印查询结果:
@Test
public void testQueryMathAll() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(QueryBuilders.matchAllQuery()) //查询所有
.addSort("age", SortOrder.DESC) //====>
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h:hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
}
//关闭连接
transportClient.close();
}
注意:
- 如果按照指定字段进行排序展示,就打乱了分数排序的规则,其分数就会失效
如果想要将查询的结果进行封装,可以这样做:将结果映射返回到对象中
@Test
public void testQueryMathAll() throws UnknownHostException, ExecutionException, InterruptedException {
List<Emp> list = new ArrayList<>();
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(QueryBuilders.matchAllQuery()) //查询所有
.addSort("age", SortOrder.DESC) //结果排序
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h:hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
Emp emp = new Emp();//=====>
emp.setName((String) h.getSourceAsMap().get("name"));
emp.setContent((String) h.getSourceAsMap().get("content"));
list.add(emp);
}
System.out.println(list);
//关闭连接
transportClient.close();
}
2. From Size分页查询
分页查询
- From 从那条记录开始 默认从0 开始 from = (pageNow-1)*size
- Size 每次返回多少条符合条件的结果 默认10
注意是将查询后的结果进行分页
@Test
public void testQueryFromAndSize() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(QueryBuilders.matchAllQuery()) //传入查询的类型
.setFrom(0) //====>
.setSize(2)
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h : hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
}
//关闭连接
transportClient.close();
}
3. source 查询返回字段
/**
* 查询返回指定字段(source) 默认返回所有:
* setFetchSource 参数1:包含哪些字段 参数2:排除哪些字段
* setFetchSource("*","age") 返回所有字段中排除age字段
* setFetchSource("name","") 只返回name字段
* setFetchSource(new String[]{},new String[]{})
*/
@Test
public void testQuerySource() throws UnknownHostException, ExecutionException, InterruptedException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(QueryBuilders.matchAllQuery()) //传入查询的类型
.setFetchSource("*","age") //====>
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h : hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
}
//关闭连接
transportClient.close();
}
_. 方法模板
后面几个由于其写法大致差不多,只是传入查询的类型不一样,我将其封装为一个方法,到时候根据查询的不同传入不同的参数即可
public void queryTemplate(QueryBuilder query) throws UnknownHostException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(query) //传入查询的类型
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h : hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
}
//关闭连接
transportClient.close();
}
4. term 指定查询
查询指定字段含有指定值
@Test
public void testTermQuery() throws UnknownHostException {
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "飞");
queryTemplate(termQueryBuilder);
}
5. range 范围查询
/**
* rang查询
* lt 小于
* lte 小于等于
* gt 大于
* gte 大于等于
*/
@Test
public void testRange() throws UnknownHostException {
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gte(10).lte(20);
queryTemplate(rangeQueryBuilder);
}
6.prefix 前缀查询
查询指定属性[根据是否分词后的结果]是否含有指定的前缀
@Test
public void testPrefix() throws UnknownHostException {
PrefixQueryBuilder prefixQueryBuilder = QueryBuilders.prefixQuery("name", "小");
queryTemplate(prefixQueryBuilder);
}
7.wildcard 通配符查询
根据通配符类型进行补全后查询
- ? :补全一个字符
- *:补全任意字符
@Test
public void testWildcardQuery() throws UnknownHostException {
WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery("content", "小*");
queryTemplate(wildcardQuery);
}
8.Ids 指定id查询
注意:这里要查询的id紧跟后面书写
@Test
public void testIds() throws UnknownHostException {
IdsQueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("1","3");
queryTemplate(queryBuilder);
}
9.fuzzy 模糊查询
根据查询的大小,可以模糊不同的个数
- 查询的个数0-2:必须和ES的词条完全匹配
- 3-5:可以模糊一个
- 大于5:可以模糊两个
Test
public void testFuzzy() throws UnknownHostException {
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("content", "努力");
queryTemplate(fuzzyQueryBuilder);
}
10.bool 复杂查询
可以有不同组合:传入的参数为同一类型
- must():查询必须满足的
- mustNot():查询相反的
- should():只要满足就行
@Test
public void testBool() throws UnknownHostException {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.termQuery("age","30"));
boolQueryBuilder.should(QueryBuilders.prefixQuery("content","努"));
queryTemplate(boolQueryBuilder);
}
11.高亮查询
高亮配置
/**
* 高亮查询
* .highlighter(highlightBuilder) 用来指定高亮设置
* requireFieldMatch(false) 开启多个字段高亮 [默认只高亮匹配部分]
* field 用来定义高亮字段
* preTags("<span style='color:red'>") 用来指定高亮前缀
* postTags("</span>") 用来指定高亮后缀
*/
@Test
public void testHighlight() throws UnknownHostException {
//===>高亮配置
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.requireFieldMatch(false);//默认只渲染匹配的字段
highlightBuilder.field("name");
highlightBuilder.field("content");
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(QueryBuilders.termQuery("content","努力")) //====>
.highlighter(highlightBuilder)//====>
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h : hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
}
//关闭连接
transportClient.close();
}
回显高亮数据
高亮数据和原数据是分开显示的,如何将高亮部分存入对象:先将原数据存入对象,再把高亮部分遍历出来替换掉需要高亮显示的部分
@Test
public void testHighlight() throws UnknownHostException {
//用于储存数据:===>
List<Emp> list = new ArrayList<>();
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.requireFieldMatch(false);//默认只渲染匹配的字段
highlightBuilder.field("name");
highlightBuilder.field("content");
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setQuery(QueryBuilders.termQuery("content", "努力")) //====>
.highlighter(highlightBuilder)//====>
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h : hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
//打印高亮部分
System.out.println(h.getHighlightFields());
//原数据
Emp emp = new Emp();
emp.setName((String) h.getSourceAsMap().get("name"));
emp.setAge((Integer) h.getSourceAsMap().get("age"));
emp.setAddress((String) h.getSourceAsMap().get("address"));
//高亮数据
Map<String, HighlightField> highlightFields = h.getHighlightFields();
if (highlightFields.containsKey("name")) {
String nameHigh = highlightFields.get("name").fragments()[0].toString();
//替换
emp.setName(nameHigh);
}
if (highlightFields.containsKey("content")) {
String contentHigh = highlightFields.get("content").fragments()[0].toString();
emp.setContent(contentHigh);
}
list.add(emp);
}
//遍历集合
System.out.println("对象方式显示高亮部分===>:");
list.forEach(emp -> {
System.out.println(emp);
});
//关闭连接
transportClient.close();
}
FilterQuery 过滤查询
过滤查询主要用于查询执行之前对大量数据进行筛选
@Test
public void testFilterQuery() throws UnknownHostException {
//创建连接
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//查询所有文档
SearchResponse searchResponse = transportClient.prepareSearch("ems")//索引
.setTypes("emp")//类型
.setPostFilter(QueryBuilders.rangeQuery("age").gte(21).lte(30))//===>过滤
.setQuery(QueryBuilders.matchAllQuery()) //===>传入查询的类型
.get();//开始查询
System.out.println("符合条件的总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最高得分:" + searchResponse.getHits().getMaxScore());
System.out.println("详细记录如下:");
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit h : hits) {
System.out.println("当前索引分数:" + h.getScore());
System.out.println("[字符串形式打印]====>" + h.getSourceAsString());
System.out.println("[map集合形式打印]====>" + h.getSourceAsMap());
}
//关闭连接
transportClient.close();
}
总结
注意setQuery的顺序:
@Test
public void testTotal() throws UnknownHostException {
//1.创建客户端
TransportClient transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("192.168.77.138"), 9300));
//es操作
SearchResponse searchResponse = transportClient.prepareSearch("ems1")
.setTypes("emp") //类型
.setFrom(0) //分页
.setSize(20)
.addSort("age", SortOrder.DESC) //排序
.setPostFilter(QueryBuilders.rangeQuery("age").gte(10).lte(30)) //过滤
.setSource(SearchSourceBuilder.searchSource().fetchSource("*", "bir"))//过滤条件
.setQuery(QueryBuilders.multiMatchQuery("小黑最爱框架部分", "name", "content"))//===>查询【有顺序要求:仅高亮在之后】
.highlighter(new HighlightBuilder().field("*").requireFieldMatch(false).preTags("<span style='color:red>").postTags("</span>")) //高亮部分[高亮搜寻字段]
.get();
System.out.println("总条数:" + searchResponse.getHits().getTotalHits());
System.out.println("最大得分:" + searchResponse.getHits().getMaxScore());
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit s : hits) {
System.out.println("原文档部分:" + s.getSourceAsString());
System.out.println("高亮部分:" + s.getHighlightFields());
}
//关闭连接
transportClient.close();
}