elasticsearch学习
Elasticsearch集群
伪集群搭建
-
解压
-
修改配置文件
jvm.options中修改占用内存,防止占用过多
-
相同的操作
node2节点:
#节点2的配置信息:
#集群名称,保证唯一
cluster.name: my-Elasticsearch
#节点名称,必须不一样
node.name: node-2
#必须为本机的ip地址
network.host: 127.0.0.1
#服务端口号,在同一机器下必须不一样
http.port: 9202
#集群间通信端口号,在同一机器下必须不一样
transport.tcp.port: 9302
#设置集群自动发现机器ip集合
discovery.zen.ping.unicast.hosts: ["127.0.0.1:9301","127.0.0.1:9302","127.0.0.1:9303"]
node3节点:
#节点3的配置信息:
#集群名称,保证唯一
cluster.name: my-Elasticsearch
#节点名称,必须不一样
node.name: node-3
#必须为本机的ip地址
network.host: 127.0.0.1
#服务端口号,在同一机器下必须不一样
http.port: 9203
#集群间通信端口号,在同一机器下必须不一样
transport.tcp.port: 9303
#设置集群自动发现机器ip集合
discovery.zen.ping.unicast.hosts: ["127.0.0.1:9301","127.0.0.1:9302","127.0.0.1:9303"]
- 启动测试
- 编写脚本快速启动
cd F:\installed\elasticsearch-cluster\elasticsearch-node1\bin
elasticsearch
- 建立索引库
ElasticSearch高级Rest客户端
java操作elasticsearch
Spring Boot集成Elasticsearch的时候,需要引入高阶客户端【elasticsearch-rest-high-level-client】【elasticsearch-rest-client】和【elasticsearch】来操作Elasticsearch,在引入起步依赖的时候,需要严格注意Elasticsearch和起步依赖的版本关系,否则在使用过程中会出很多问题
步骤:
-
导坐标
创建工程
-
配置文件
<!--elasticsearch的高级别rest客户端-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.8.0</version>
</dependency>
<!--elasticsearch的rest客户端-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>6.8.0</version>
</dependency>
<!--elasticsearch的核心jar包-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.0</version>
</dependency>
- 使用
将ElasticSearch的客户端对象,注入Spring的容器
@Configuration
@Component
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticsearchRestConfiguration {
//约定大于配置
private String hostname = "127.0.0.1";
private int port = 9200;
//将RestHighLevelClient注入容器
@Bean
public RestHighLevelClient client(){
//对当前的url地址的封装对象
HttpHost httpHost = new HttpHost(hostname, port, "http");
//创建rest客户端构建器对象
RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
//创建高级客户端对象
return new RestHighLevelClient(restClientBuilder);
}
}
配置文件
#ip
elasticsearch.host: 127.0.0.1
#端口
elasticsearch.port: 9200
创建索引索引库
1、新增索引库
目标:使用ElasticSearch的高阶客户端,编写Java代码,创建索引库
分析:
Java high level客户端的操作,是模仿我们通过发送请求调用RESTful接口调用的方式,本质还是请求获取响应。
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo01IndexOperation {
/*
注入高级客户端
*/
@Autowired
private RestHighLevelClient client;
/**
* 目标:创建索引库
*
* 1.创建请求对象
* 2.客户端对象发送请求,返回响应对象
* 3.打印响应对象结果信息
* 4.关闭客户端,释放资源
*/
@Test
public void createIndex() throws IOException {
//创建请求对象
CreateIndexRequest request = new CreateIndexRequest("ahucom");
//注入客户端对象,执行操作,返回响应对象
IndicesClient indicesClient = client.indices(); //返回的是创建索引的客户端对象,索引的新增删除配置映射等操作
//执行创建索引的请求 参数1创建索引的请求对象 参数2当前请求对象的配置(请求头【空】,响应内容的缓存大小100m,异常的回调方法【默认空】)
CreateIndexResponse response = indicesClient.create(request, RequestOptions.DEFAULT);
//打印响应结果
System.out.println("acknowlwdge::" + response.isAcknowledged());
System.out.println("index::" + response.index());
//关闭客户端,bean对象的声明周期
client.close();
}
}
使用了默认的配置
执行结果:
发送请求中,传入请求对象的同时还设置了一个RequestOptions对象的静态成员变量DEFAULT。其含义是,配置当前请求选项为默认值。
其中RequestOptions对象的作用是用来配置请求,主要配置项目有请求头,缓冲区大小(默认100M),异常处理器(warningsHandler)。默认情况下,缓冲区大小100MB,请求头及异常处理器为空。
2、查看索引库
/**
* 查询索引库
*/
@Test
public void getIndex() throws IOException {
//1.创建请求对象
GetIndexRequest request = new GetIndexRequest("ahucom");
//2.客户端执行请求发送,返回响应对象
IndicesClient indices = client.indices();
GetIndexResponse response = indices.get(request, RequestOptions.DEFAULT);
//3.打印信息
System.out.println("aliases::" + response.getAliases());
System.out.println("mappings::" + response.getMappings());
System.out.println("settings::" + response.getSettings());
//4.关闭客户端
// client.close();
}
执行结果:
设置声明周期中的销毁执行close客户端的操作,就不用手动关闭了
3、删除索引库
/**
* 删除索引库
*/
@Test
public void deleteIndex() throws IOException {
//1.创建请求对象
DeleteIndexRequest request = new DeleteIndexRequest("ahucom");
//2.客户端执行发送请求
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
//3.打印信息
System.out.println("ack::" + response.isAcknowledged());
//4.关闭客户端
}
配置映射
当配置Spring的ioc容器中的RestHighLevelClient对象的销毁执行方法之后,每次容器销毁对象时,必然会执行close方法,所以我们在使用完对象,可以不用每次手动关闭客户端。
1、配置映射
RestHighLevelClient配置映射,与kibana略有区别。在客户端中配置映射,不支持设置类型type。不设置type,并不代表没有,而是默认的type为_doc
。
//配置映射,XContentBuilder
@Test
public void createMappingMethodTwo() throws IOException {
//1.创建请求对象,索引库、类型、请求体
PutMappingRequest request = new PutMappingRequest("ahucom1");
//在6.8.0版本不支持设置type,默认值_doc
XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
jsonBuilder.startObject()
.startObject("properties")
.startObject("title")
.field("type","text").field("analyzer","ik_max_word")
.endObject()
.startObject("subtitle")
.field("type","text").field("analyzer","ik_max_word")
.endObject()
.startObject("category")
.field("type","keyword")
.endObject()
.startObject("brand")
.field("type","keyword")
.endObject()
.startObject("images")
.field("type","keyword").field("index",false)
.endObject()
.startObject("price")
.field("type","float")
.endObject()
.endObject()
.endObject();
request.source(jsonBuilder);
//2.客户端发送请求,获取响应对象
AcknowledgedResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
//3.打印结果信息
System.out.println("ack::" + response.isAcknowledged());
}
执行结果:
第二种方式:
//配置映射,字符串拼接
@Test
public void createMapping() throws IOException {
//1.创建请求对象,索引库、类型、请求体
PutMappingRequest request = new PutMappingRequest("ahucom");
//在6.8.0版本不支持设置type,默认值_doc
String requestbodyJsonStr = "{\n" +
" \"properties\": {\n" +
" \"title\":{\n" +
" \"type\":\"text\",\n" +
" \"analyzer\": \"ik_max_word\",\n" +
" \"index\": true,\n" +
" \"store\": false\n" +
" },\n" +
" \"subtitle\":{\n" +
" \"type\":\"text\",\n" +
" \"analyzer\": \"ik_max_word\",\n" +
" \"index\": true,\n" +
" \"store\": false\n" +
" },\n" +
" \"images\":{\n" +
" \"type\": \"keyword\",\n" +
" \"index\": false,\n" +
" \"store\": false\n" +
" },\n" +
" \"price\":{\n" +
" \"type\":\"double\",\n" +
" \"index\": true,\n" +
" \"store\": false\n" +
" }\n" +
" }\n" +
"}";
request.source(requestbodyJsonStr, XContentType.JSON);
//2.客户端发送请求,获取响应对象
AcknowledgedResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
//3.打印结果信息
System.out.println("ack::" + response.isAcknowledged());
}
执行结果:
2、查看映射
@Test
public void getMapping() throws IOException {
//1.创建请求对象,查看映射
GetMappingsRequest request = new GetMappingsRequest();
//设置索引库名
request.indices("ahucom");
//2.客户端发送请求,获取响应对象
GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT);
System.out.println("mapping::" + response.mappings());
System.out.println("source::" + response.mappings().get("ahucom").getSourceAsMap());
}
执行结果:
文档操作
1、创建文档
创建实体:
@Data
@Builder
public class Goods {
private Long id;//商品的唯一标识
private String title;//标题
private String subtitle;//子标题
private String category;//分类
private String brand;//品牌
private Double price;//价格
private String images;//图片地址
//...getter , setter , toString
}
创建操作代码:
@Test
public void saveDoc() throws IOException {
//1.创建请求对象 索引库明、类型名、主键id
IndexRequest request = new IndexRequest().index("ahucom").type("_doc").id("1");
//请求体三种方式:1.直接写入字符串 2.将对象转为字符串 3.直接在source中写入k-v形式的参数
//将对象转为json字符串
Goods goods = Goods.builder().id(1L).title("小米手机").category("手机").brand("小米").price(1999.0).build();
ObjectMapper objectMapper = new ObjectMapper();
String goodsJsonStr = objectMapper.writeValueAsString(goods);
//直接在source中写入key-value参数
request.source(goodsJsonStr, XContentType.JSON);
//2.客户端发送请求,获取响应对象
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//3.打印结果信息
System.out.println("_index::" + response.getIndex());
System.out.println("_type::" + response.getType());
System.out.println("_id::" + response.getId());
System.out.println("_result::" + response.getResult());
}
执行结果:
直接在source中插入:
@Test
public void saveDoc() throws IOException {
//1.创建请求对象 索引库明、类型名、主键id
IndexRequest request = new IndexRequest().index("ahucom").type("_doc");
//请求体三种方式:1.直接写入字符串 2.将对象转为字符串 3.直接在source中写入k-v形式的参数
//将对象转为json字符串
// Goods goods = Goods.builder().id(1L).title("小米手机").category("手机").brand("小米").price(1999.0).build();
// ObjectMapper objectMapper = new ObjectMapper();
// String goodsJsonStr = objectMapper.writeValueAsString(goods);
// request.source(goodsJsonStr, XContentType.JSON);
//直接在source中写入key-value参数
request.source(XContentType.JSON, "title","华为荣耀","id","2","brand","华为","category","手机","price","2000");
//2.客户端发送请求,获取响应对象
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//3.打印结果信息
System.out.println("_index::" + response.getIndex());
System.out.println("_type::" + response.getType());
System.out.println("_id::" + response.getId());
System.out.println("_result::" + response.getResult());
}
2、修改文档
主键id相同,修改数据
@Test
public void update() throws IOException {
//1.创建请求对象 索引库明、类型名、主键id
UpdateRequest request = new UpdateRequest().index("ahucom").type("_doc").id("1");
//直接在source中写入key-value参数
request.doc(XContentType.JSON, "title","锤子","id","2","brand","华为","category","手机","price","2000");
//2.客户端发送请求,获取响应对象
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
//3.打印结果信息
System.out.println("_index::" + response.getIndex());
System.out.println("_type::" + response.getType());
System.out.println("_id::" + response.getId());
System.out.println("_result::" + response.getResult());
}
执行结果:
3、根据id查询文档
//查询文档
@Test
public void query() throws IOException {
GetRequest request = new GetRequest().index("ahucom").type("_doc").id("1");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println("_index::" + response.getIndex());
System.out.println("_type::" + response.getType());
System.out.println("_id::" + response.getId());
System.out.println("_result::" + response.getSourceAsString());
}
执行结果:
4、删除文档
@Test
public void delete() throws IOException {
DeleteRequest request = new DeleteRequest().index("ahucom").type("_doc").id("1");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
}
执行结果:
5、批量操作bulk
//批量新增
@Test
public void bulkSave() throws IOException {
//创建请求对象
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("comahu").type("_doc").id("1").source(XContentType.JSON,"title","小米手机"));
request.add(new IndexRequest().index("comahu").type("_doc").id("2").source(XContentType.JSON,"title","锤子手机"));
request.add(new IndexRequest().index("comahu").type("_doc").id("3").source(XContentType.JSON,"title","苹果手机"));
//客户端发送请求
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
//打印信息
System.out.println("took::" + response.getTook());
System.out.println("items::" + response.getItems());
}
//批量删除
@Test
public void bulkDelelte() throws IOException {
//创建请求对象
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("ahucom").type("_doc").id("1"));
request.add(new DeleteRequest().index("ahucom").type("_doc").id("2"));
request.add(new DeleteRequest().index("ahucom").type("_doc").id("3"));
//客户端发送请求
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
//打印信息
System.out.println("took::" + response.getTook());
System.out.println("items::" + response.getItems());
}
执行结果:
新增
删除
高级Rest客户端-请求体查询
模拟数据
/**
* 初始化查询数据
*/
@Test
public void initData() throws IOException {
//批量新增操作
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","大米手机","images","http://image.leyou.com/12479122.jpg","price",3288,"category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","小米手机","images","http://image.leyou.com/12479122.jpg","price",2699,"category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","小米电视4A","images","http://image.leyou.com/12479122.jpg","price",4288,"category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","华为手机","images", "http://image.leyou.com/12479122.jpg","price", 5288,"subtitle", "小米","category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","apple手机","images","http://image.leyou.com/12479122.jpg","price",5899.00,"category","手机","brand","小米"));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println("took::"+response.getTook());
System.out.println("Items::"+response.getItems());
}
高级Rest客户端-请求体查询
模拟数据
/**
* 初始化查询数据
*/
@Test
public void initData() throws IOException {
//批量新增操作
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","大米手机","images","http://baidu.com/12479122.jpg","price",3288,"category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","小米手机","images","http://baidu.com/12479122.jpg","price",2699,"category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","小米电视4A","images","http://baidu.com/12479122.jpg","price",4288,"category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","华为手机","images", "http://baidu.com/12479122.jpg","price", 5288,"subtitle", "小米","category","手机","brand","小米"));
request.add(new IndexRequest().type("_doc").index("ahu3").source(XContentType.JSON,"title","apple手机","images","http://baidu.com/12479122.jpg","price",5899.00,"category","手机","brand","小米"));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println("took::"+response.getTook());
System.out.println("Items::"+response.getItems());
}
基本查询
打印结果
/**
* 打印结果
* @param response
*/
private void printResult(SearchResponse response) {
SearchHits hits = response.getHits();
System.out.println("took::" + response.getTook());
System.out.println("timeout::" + response.isTimedOut());
System.out.println("hits::" + hits.getTotalHits());
System.out.println("maxScore::" + hits.getMaxScore());
System.out.println("hits===================>");
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println("<======================");
}
1、匹配查询(matchAll)
/**
* 请求体查询-基本查询
* 1.查询所有
* 2.match查询,带分词器的查询
* 3.multi_match查询,查询多个字段
* 4.term查询,关键词精确匹配
* 5.terms查询,多个关键词精确匹配
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo05RequestBodyQuery_Basic {
//注入ES客户端对象
@Autowired
private RestHighLevelClient client;
/**
* 查询所有
* 1.创建请求对象:查询所有
* ahu
* 设置类型type
* 2.创建查询请求体构建器
* 设置请求体
* 3.客户端发送请求,获取响应对象
* 4.打印响应结果
*/
//match_all
@Test
public void matchall() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//请求体,使用了构建者设计模式
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
request.source(searchSourceBuilder);
//2.客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
SearchHits hits = response.getHits();
System.out.println("took::" + response.getTook());
System.out.println("timeout::" + response.isTimedOut());
System.out.println("hits::" + hits.getTotalHits());
System.out.println("maxScore::" + hits.getMaxScore());
System.out.println("hits===================>");
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println("<======================");
}
}
执行结果:
2、匹配查询(match)
/**
* 匹配查询,带分词器的查询
* 分词后关键词之间的关系,or(默认),and
* 1.创建请求对象:匹配查询
* ahu
* 设置类型type
* 2.创建查询请求体构建器
* 设置请求体
* 3.客户端发送请求,获取响应对象
* 4.打印响应结果
*/
@Test
public void matchQuery() throws IOException {
//1.创建请求对象:匹配查询
SearchRequest request = new SearchRequest();
request.types("_doc");
request.indices("ahu4");
//2.创建查询请求体构建器
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//匹配查询,设置分词后关键词的查询关系,默认是or
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", "小米手机")
.operator(Operator.AND);
sourceBuilder.query(matchQueryBuilder);
//设置请求体
request.source(sourceBuilder);
//3.客户端发送请求,获取响应对象
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//4.打印响应结果
printResult(response);
}
//打印结果信息
public void printResult(SearchResponse response) {
SearchHits hits = response.getHits();
System.out.println("took::"+response.getTook());
System.out.println("time_out::"+response.isTimedOut());
System.out.println("total::"+hits.getTotalHits());
System.out.println("max_score::"+hits.getMaxScore());
System.out.println("hits::::>>");
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
System.out.println(sourceAsString);
}
System.out.println("<<::::");
}
执行结果:
精确查询:
//match
@Test
public void match() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//请求体,使用了构建者设计模式
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//match带分词器
searchSourceBuilder.query(QueryBuilders.matchQuery("title","小米手机").operator(Operator.AND));
request.source(searchSourceBuilder);
//2.客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
结果:
3、匹配查询(multi_match)
/**
* 多字段匹配查询,查询title和subtitle
* 1.创建请求对象:多字段匹配查询
* ahu
* 设置类型type
* 2.创建查询请求体构建器
* 设置请求体
* 3.客户端发送请求,获取响应对象
* 4.打印响应结果
*/
//multimatch
@Test
public void multiMatch() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//请求体,使用了构建者设计模式
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//match带分词器
searchSourceBuilder.query(QueryBuilders.multiMatchQuery("小米","title","subtitle"));
request.source(searchSourceBuilder);
//2.客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
4、关键词精确匹配查询(term)
//term
@Test
public void term() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//请求体,使用了构建者设计模式
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//match带分词器
searchSourceBuilder.query(QueryBuilders.termQuery("price",2699));
request.source(searchSourceBuilder);
//2.客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
5、多关键词精确匹配查询(terms)
/**
* 多关键词精确查询
* 1.创建请求对象:多关键词精确查询
* ahu
* 设置类型type
* 2.创建查询请求体构建器
* 设置请求体
* 3.客户端发送请求,获取响应对象
* 4.打印响应结果
*/
//terms
@Test
public void terms() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//请求体,使用了构建者设计模式
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//match带分词器
searchSourceBuilder.query(QueryBuilders.termsQuery("title","手机","小米"));
request.source(searchSourceBuilder);
//2.客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
结果过滤,排序,分页
//分页和排序
@Test
public void includesSources() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//请求体,使用了构建者设计模式
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//matchAll查询所有
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
//分页信息
searchSourceBuilder.size(2);
searchSourceBuilder.from(0);
//排序信息
searchSourceBuilder.sort("price", SortOrder.ASC);
//查询字段过滤
String[] includes = {"title","subtitle","price"};
String[] excludes = {"images"};
searchSourceBuilder.fetchSource(includes, excludes);
request.source(searchSourceBuilder);
//2.客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
高级查询
1、布尔查询(bool)
目标:查询title中必须包含小米,一定不含有电视,应该含有手机的所有商品
/**
* 请求体查询-高级别查询
* 1.布尔查询
* 2.范围查询
* 3.模糊查询
*/
//高级查询
@Test
public void boolAndRangeAndFuzzyQuery() throws IOException {
//创建搜索对象
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//构建插叙的请求体
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//高级查询的三种方式
//bool查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//must
boolQueryBuilder.must(QueryBuilders.matchQuery("title","小米"));
//must not
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("title","电视"));
//should
boolQueryBuilder.should(QueryBuilders.matchQuery("title","手机"));
searchSourceBuilder.query(boolQueryBuilder);
request.source(searchSourceBuilder);
//2.客户端发送数据
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
2、范围查询(range)
目标:查询价格大于2千,小于4千的所有商品
/**
* 范围查询
* 1.创建请求对象:范围查询
* 设置索引库name
* 设置类型type
* 2.创建查询请求体构建器
* 设置请求体
* 3.客户端发送请求,获取响应对象
* 4.打印响应结果
*/
//高级查询
@Test
public void boolAndRangeAndFuzzyQuery() throws IOException {
//创建搜索对象
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//构建插叙的请求体
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//高级查询的三种方式
//bool查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//must
boolQueryBuilder.must(QueryBuilders.matchQuery("title","小米"));
//must not
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("title","电视"));
//should
boolQueryBuilder.should(QueryBuilders.matchQuery("title","手机"));
//范围查询
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");
rangeQueryBuilder.lt(5000);
rangeQueryBuilder.gt(3000);
searchSourceBuilder.query(rangeQueryBuilder);
request.source(searchSourceBuilder);
//2.客户端发送数据
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
3、模糊查询(fuzzy)
//高级查询
@Test
public void boolAndRangeAndFuzzyQuery() throws IOException {
//创建搜索对象
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//构建插叙的请求体
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//高级查询的三种方式
//bool查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//must
boolQueryBuilder.must(QueryBuilders.matchQuery("title","小米"));
//must not
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("title","电视"));
//should
boolQueryBuilder.should(QueryBuilders.matchQuery("title","手机"));
//范围查询
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");
rangeQueryBuilder.lt(5000);
rangeQueryBuilder.gt(3000);
//模糊查询
FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("title", "appla");
searchSourceBuilder.query(fuzzyQueryBuilder);
request.source(searchSourceBuilder);
//2.客户端发送数据
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//3.打印结果信息
printResult(response);
}
执行结果:
高亮查询(Highlighter)
/**
* 请求体查询-高亮查询
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo05HighlighterQuery {
@Autowired
private RestHighLevelClient client;
@Test
public void getHighLight() throws IOException {
SearchRequest request = new SearchRequest().indices("ahucom").types("_doc");
//构建请求体
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//terms查询
sourceBuilder.query(QueryBuilders.matchQuery("title","电视"));
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color=red>");
highlightBuilder.postTags("</font>");
//设置高亮的字段
highlightBuilder.field("title");
//设置高亮查询
sourceBuilder.highlighter(highlightBuilder);
//设置请求体
request.source(sourceBuilder);
//客户端发送请求
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//打印结果信息
printResult(response);
}
/**
* 打印结果
* @param response
*/
private void printResult(SearchResponse response) {
SearchHits hits = response.getHits();
System.out.println("took::" + response.getTook());
System.out.println("timeout::" + response.isTimedOut());
System.out.println("hits::" + hits.getTotalHits());
System.out.println("maxScore::" + hits.getMaxScore());
System.out.println("hits===================>");
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
System.out.println("<======================");
System.out.println("hits:::::::::::::::::>");
hits.forEach(new Consumer<SearchHit>() {
@Override
public void accept(SearchHit hit) {
System.out.println(hit.getSourceAsString());
//抽取高亮的结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
System.out.println(highlightFields);
}
});
System.out.println("<:::::::::::::::::");
}
}
执行结果: