ElasticSearch
ik分词器:
ik分词器的安装,将ik分词器下载并解压,新建文件夹ik,将解压内容放进ik文件夹中,将ik文件夹放在es安装路径的plugin文件夹中
GET _analyze
{
"analyzer": "ik_smart",
"text":"中国共产党"
}
GET _analyze
{
"analyzer": "ik_max_word",
"text":"中国共产党"
}
ik_smart:最小切片划分
ik_max_word:最细粒度划分
ik分词器增加自己的配置
在es的安装目录中/elasticsearch/plugins/ik/config,创建后缀名为.dic的文件,将自己配置的词语写到.dic文件中,
文件中的内容:
docker下安装Elasticsearch和kibana
1、将云端镜像拉取到本地:
docker pull elasticsearch
2、安装elasticsearch
docker run -it --name elasticsearch -d -p 9200:9200 -p 9300:9300 -p 5601:5601 elasticsearch
docker run -id --name es -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node”
elasticsearch:7.4.0
3、将kibana从云端拉取到本地
docker pull kibana
4、安装kibana
docker run -it -d -e ELASTICSEARCH_URL=http://192.168.58.20:9200 --name kibana --network=container:elasticsearch kibanadocker run -it -d -e ELASTICSEARCH_URL=http://192.168.58.20:9200 --name kibana --network=container:elasticsearch kibana
docker run -id --name kibana --link es:elasticsearch -p 5601:5601 kibana:7.4.0
一、初步检索
1、保存文档
PUT testdb //创建索引,未添加值
{
"mappings":{
"properties": {
"name":{
"type":"text"
},
"desc":{
"type":"keyword"
}
}
}
}
PUT /human/user/1
{
"name":"tfxing",
"age":18,
"desc":"优秀的中国五四好青年"
}
2、查询数据
GET /human/user/1
GET human/user/_search?q=name:tfxing
##################
{
"_index" : "human",
"_type" : "user",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "tfxing",
"age" : 18,
"desc" : "优秀的中国五四好青年"
}
}
3、更新文档
3.1、put更新会将没有更新值的字段去除,只要执行了,_version就会更新
3.2、post更新只会更新写了的字段,没写的字段会保存原来的值,post修改如果字段没有变的会,_version不会更新
PUT human/user/1
{
"name":"tfxing",
"age":20
}
############################
{
"_index" : "human",
"_type" : "user",
"_id" : "1",
"_version" : 2,
"_seq_no" : 1,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "tfxing",
"age" : 20
}
}
POST human/user/2/_update
{
"doc": {
"name":"zxyan",
"age":19
}
}
//--------------愿来的值----------
{
"_index" : "human",
"_type" : "user",
"_id" : "2",
"_version" : 1,
"_seq_no" : 2,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "zxyan",
"age" : 18,
"desc" : "优秀的中国五四好青年"
}
}
//---------------修改后的值-----------
{
"_index" : "human",
"_type" : "user",
"_id" : "2",
"_version" : 4,
"_seq_no" : 5,
"_primary_term" : 1,
"found" : true,
"_source" : {
"name" : "zxyan",
"age" : 19,
"desc" : "优秀的中国五四好青年"
}
}
4、复杂查询
内嵌结构
4.1、字段过滤(_source)
GET human/user/_search
{
"query":{
"match":{ //match:模糊查询
"name":"tfxing"
}
},
"_source":["name"]
}
GET human/user/_search
{
"query":{
"match":{
"name":"tfxing"
}
},
"_source":["name","age"]
}
#######查询结果########
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.4599355,
"hits" : [
{
"_index" : "human",
"_type" : "user",
"_id" : "1",
"_score" : 1.4599355,
"_source" : {
"name" : "tfxing"
}
}
]
}
}
4.2、排序(sort)
GET human/user/_search
{
"_source":["name","age"],
"sort":[
{
"age":{
"order":"asc" //按age升序排序,desc:降序
}
}
]
}
#####查询结果######
4.3、分页(from , size)从第几个数据开始查,返回多少条数据,索引下标从0开始
GET human/user/_search
{
"_source":["name","age"],
"sort":[
{
"age":{
"order":"asc"
}
}
],
"from":0,
"size":2
}
4.4、布尔查询(bool):多条件查询
must(and),所有条件都要符合,相当于sql中的and
should(or),
GET human/user/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"age":20
}
}
]
}
}
}
should:等价与sql中的or,条件中满足一个即可
GET human/user/_search
{
"query":{
"bool":{
"should":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"age":18
}
}
]
}
}
}
########结果集######
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.4599355,
"hits" : [
{
"_index" : "human",
"_type" : "user",
"_id" : "1",
"_score" : 1.4599355,
"_source" : {
"name" : "tfxing",
"age" : 20
}
},
{
"_index" : "human",
"_type" : "user",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"name" : "zxyan",
"age" : 18,
"desc" : "优秀的中国五四好青年"
}
}
]
}
}
must_not:不满足
GET human/user/_search
{
"query":{
"bool":{
"must_not":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"age":20
}
}
]
}
}
}
4.5、过滤查询(range) gt:大于、gte:大于等于、lt:小于、lte:小于等于
GET human/user/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"name":"张三"
}
}
],
"filter":{
"range":{
"age":{
"gte":22 //gt:大于、gte:大于等于、lt:小于、lte:小于等于
}
}
}
}
}
}
4.6、模糊查询(match)多个条件使用空格隔开
只要满足其一就能被查询出来
GET human/user/_search
{
"query":{
"match":{
"desc":"优秀 法外"
}
}
}
4.7、通过倒排索引指定的词条进行精确查询(term)
term:直接查询精确的
match:会使用分词器解析,(先分析文档,然后通过分析的文档进行查询)
keyword字段类型不会被分词器解析
GET human/user/_search
{
"query":{
"bool":{
"should":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"name":"zxyan"
}
}
]
}
}
}
4.8、高亮查询
搜索相关的结果可以高亮显示
GET human/user/_search
{
"query":{
"match":{
"name":"tfxing"
}
},
"highlight":{
"pre_tags":"<p class='key' style='color:red'>", //搜索结果前缀 自定义搜索条件
"post_tags":"</p>", //后缀
"fields":{
"name":{}
}
}
}
#######查询结果#######
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.4599355,
"hits" : [
{
"_index" : "human",
"_type" : "user",
"_id" : "1",
"_score" : 1.4599355,
"_source" : {
"name" : "tfxing",
"age" : 20
},
"highlight" : {
"name" : [
"<p class='key' style='color:red'>tfxing</p>"
]
}
}
]
}
}
二、ES继承springboot
1、导入pom依赖
<!--引入es的坐标-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.0</version>
</dependency>
1、_cat(带_的都叫元数据)
GET/_cat/nodes: 查看所有节点
GET/_cat/health: 查看es健康状况
GET/_cat/master: 查看主节点
GET/_cat/indices:查看所有索引(类似show databases)
2、索引一个文档(保存)
保存一个数据,保存在那个索引的哪个类型下
PUT/customer/external/1
例:PUT http://192.168.58.20:9200/customer/external/1 { “name”:“tfxing”}
发送多次为更新,使用put和post都可以,如果不指定id,会生成一个随机id
3、查询文档
GET customer/external
4、更新文档
post加_update的方式会对比原来的数据,如果没有改变,则_sql_no和_version不会改变
注意:使用post加_update的方式更新需要加上"doc":{“name”:“tfxing”},需要加doc,而put和post不带_update则不需要加doc
而put和post不带_update更新不会对比原来的数据,_ sql_no和_version会改变
5、删除文档&索引
删除指定文档和删除整个索引(整个表)
6、bulk批量API
post请求,一个大括号代表一个索引,两行为一个整体,
delete删除没有请求体,所以只有一行
create:创建,title行为创建的数据
index:保存,title行为需要保存的数据
update:更新,“_retry_on_conflict”:3:表示如果更新失败,重试3次
二、MatchAll查询流程
@Test
public void matchAll() throws Exception{
//2.构建查询请求对象,指定查询的索引名称
SearchRequest searchRequest = new SearchRequest("goods");
/*
3.添加查询条件构建器 SearchSourceBuilder,
4.创建查询条件构建起SearchSourceBuilder,
5.指定查询条件,
6.查询条件
*/
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
//1.查询,获取查询结果
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//7.获取Hits数据 数组
for (SearchHit hit : searchResponse.getHits().getHits()) {
Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
System.out.println(goods);
}
}
1、开发流程:
1.1、创建moudle
2.2、导入pom依赖
<?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>
<artifactId>spiringbootEs</artifactId>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<!--<mysql.version>8.0.18</mysql.version>-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--引入es的坐标-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
1.3、yml配置
elasticsearch:
host: 192.168.58.20
port: 9200
spring:
datasource:
url: jdbc:mysql:///elasticsearch?serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations:classpath: com/tfxing/mapper/*Mapper.xml
type-aliases-package: com.tfxing.bean
集群用逗号隔开
1.4、编写主启动类
package com.tfxing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
1.5、编写实体类
package com.tfxing.bean;
import java.util.Date;
import java.util.Map;
@Data
public class Goods {
private int id;
private String title;
private double price;
private int stock;
private int saleNum;
private Date createTime;
private String categoryName;
private String brandName;
private Map spec;
private String specStr;
}
1.6、编写config类
package com.tfxing.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ESConfig {
private String host;
private int port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Bean
public RestHighLevelClient client(){
return new RestHighLevelClient(RestClient.builder(
new HttpHost(
host,
port,
"http"
)
));
}
}
1.7、编写mapper层
package com.tfxing.mapper;
import com.tfxing.bean.Goods;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface GoodsMapper {
List<Goods> findAll();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tfxing.mapper.GoodsMapper">
<select id="findAll" resultType="goods">
select
`id` ,
`title` ,
`price` ,
`stock` ,
`saleNum` ,
`createTime` ,
`categoryName`,
`brandName` ,
`spec` as specStr
from goods
</select>
</mapper>
1.8、测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestES {
@Autowired
private RestHighLevelClient client;
@Autowired
private GoodsMapper goodsMapper;
@Test
public void testClient(){
System.out.println(client);
}
}
三、各类功能的实现
1、创建索引
/**
* 创建索引
*/
@Test
public void addIndices() throws Exception{
//1.使用client获取操作索引的对象
IndicesClient indices = client.indices();
//2.具体操作,获取返回值,teacher参数相当于es的表名
CreateIndexRequest request = new CreateIndexRequest("teacher");
CreateIndexResponse response = indices.create(request, RequestOptions.DEFAULT);
//3.根据返回值判断是否成功上面的操作
System.out.println(response.isAcknowledged());
}
2、添加索引和映射
/**
* 添加索引和映射
*/
@Test
public void addIndicesAndMapping() throws Exception{
//1.使用client获取操作索引的对象
IndicesClient indices = client.indices();
//2.具体操作,并取得返回值,使用indices.create()方法,需要传入一个CreateIndexRequst和一个指令对象RequstOptions
CreateIndexRequest indexRequest = new CreateIndexRequest("student");
//2.1、设置mappings
String mapping = "{\n" +
" \"properties\" : {\n" +
" \"address\" : {\n" +
" \"type\" : \"text\",\n" +
" \"analyzer\" : \"ik_max_word\"\n" +
" },\n" +
" \"age\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"name\" : {\n" +
" \"type\" : \"keyword\"\n" +
" }\n" +
" }\n" +
" }";
indexRequest.mapping(mapping, XContentType.JSON);
//3、根据返回值判断是否成功执行
CreateIndexResponse response = indices.create(indexRequest, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
3、查询索引
/**
* 查询索引
*/
@Test
public void queryIndex() throws Exception{
IndicesClient indices = client.indices();
GetIndexResponse response = indices.get(new GetIndexRequest("student"), RequestOptions.DEFAULT);
//获取结果
Map<String, MappingMetaData> mappings = response.getMappings();
for (String key : mappings.keySet()) {
System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
}
}
4、删除索引
/**
* 删除索引
*/
@Test
public void testDelete() throws Exception{
IndicesClient indices = client.indices();
AcknowledgedResponse response = indices.delete(new DeleteIndexRequest("teacher"), RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
5、判断索引是否存在
/**
* 判断索引是否存在
*/
@Test
public void testExistIndex() throws Exception{
IndicesClient indices = client.indices();
boolean exists = indices.exists(new GetIndexRequest("person"), RequestOptions.DEFAULT);
System.out.println(exists);
}
6、添加文档,使用map作为数据
/**
* 添加文档,使用map作为数据
*/
@Test
public void addDocByMap() throws Exception{
//数据对象
Map data = new HashMap();
data.put("address","深圳宝安");
data.put("name","tfxing");
data.put("age",18);
//1.获取操作文档的对象
IndexRequest request = new IndexRequest("student").id("1").source(data);
//2.添加数据,获取结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println(response.getId());
}
7、添加文档,使用对象作为数据
/**
* 使用对象进行添加操作
* @throws Exception
*/
@Test
public void addDocByPojo() throws Exception{
Student student = new Student("2","laow",19,"江西赣州");
//将对象转换成json数据
String studentJson = JSON.toJSONString(student);
//获取操作文档的对象
IndexResponse response = client.index(new IndexRequest("student").id(student.getId()).source(studentJson,XContentType.JSON), RequestOptions.DEFAULT);
System.out.println(response.getId());
}
8、修改文档
/**
* 修改文档
*/
@Test
public void updateDoc() throws Exception{
Student student = new Student("2","lwang",19,"江西赣州");
//将对象转换成json数据
String studentJson = JSON.toJSONString(student);
//获取操作文档的对象
IndexResponse response = client.index(new IndexRequest("student").id(student.getId()).source(studentJson,XContentType.JSON), RequestOptions.DEFAULT);
System.out.println(response.getId());
}
9、根据id查询文档
/**
* 根据id查询文档
*/
@Test
public void findById() throws Exception{
GetResponse response = client.get
(new GetRequest("student", "1")
, RequestOptions.DEFAULT);
Map<String, Object> source = response.getSourceAsMap();
System.out.println(source);
}
10、根据id删除文档
/**
* 根据id删除文档
*/
@Test
public void delDoc() throws Exception{
DeleteResponse response = client.delete(new DeleteRequest("student", "1"), RequestOptions.DEFAULT);
System.out.println(response.status());
}
11、测试term条件查询
/**
*测试term条件查询
*/
@Test
public void term() throws Exception{
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("address", "江西深圳")));
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
SearchHit[] hits1 = hits.getHits();
for (SearchHit hit : hits1) {
String sourceAsString = hit.getSourceAsString();
Student student = JSON.parseObject(sourceAsString,Student.class);
System.out.println(student);
}
}
返回结果
12、测试Operator查询
/**
* 测试Operator查询
*/
@Test
public void test1() throws Exception{
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchQuery("address","江西深圳").operator(Operator.OR)));
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits1 = response.getHits().getHits();
for (SearchHit hit : hits1) {
String sourceAsString = hit.getSourceAsString();
Student student = JSON.parseObject(sourceAsString,Student.class);
System.out.println(student);
}
}
13、批量操作
/**
* 批量操作
*/
@Test
public void bluk() throws Exception{
//1.创建bulkRequst对象,整合所有操作
BulkRequest bulkRequest = new BulkRequest();
//添加对应的操作
//删除一条数据
bulkRequest.add(new DeleteRequest("student","1"));
//添加一条数据
String aJsonStr = JSON.toJSONString(new Student("3", "aaa", 20, "北京昌平"));
IndexRequest indexStudenta = new IndexRequest("student").id("3").source(aJsonStr, XContentType.JSON);
bulkRequest.add(indexStudenta);
//添加一条数据
IndexRequest indexRequest = new IndexRequest("student").id("4").source(JSON.toJSONString(new Student("4", "bbb", 21, "上海")), XContentType.JSON);
bulkRequest.add(indexRequest);
//执行操作,并判断是否执行成功
BulkResponse bulk = client.bulk(bulkRequest,RequestOptions.DEFAULT);
System.out.println(bulk.status());
}
14、导入数据
/**
* 导入数据
*/
@Test
public void insetData() throws Exception{
List<Goods> goodsList = goodsMapper.findAll();
BulkRequest bulkRequest = new BulkRequest();
for (Goods goods : goodsList) {
Map map = JSON.parseObject(goods.getSpecStr(), Map.class);
goods.setSpec(map);
String goodsJsonStr = JSON.toJSONString(goods);
IndexRequest indexRequest = new IndexRequest("goods").id(goods.getId() + "").source(goodsJsonStr, XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.status());
}
15、使用matchAll查询
/**
* 使用matchAll查询
*/
@Test
public void matchAll() throws Exception{
//2.构建查询请求对象,指定查询的索引名称
SearchRequest searchRequest = new SearchRequest("goods");
/*
3.添加查询条件构建器 SearchSourceBuilder,
4.创建查询条件构建起SearchSourceBuilder,
5.指定查询条件,
6.查询条件
*/
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
//1.查询,获取查询结果
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//7.获取Hits数据 数组
for (SearchHit hit : searchResponse.getHits().getHits()) {
Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
System.out.println(goods);
}
}
16、模糊查询
/**
* 模糊查询
*/
@Test
public void wildCardQuery() throws Exception{
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.wildcardQuery("name","*x*")));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : searchResponse.getHits().getHits()) {
Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
System.out.println(student);
}
}
17、范围查询
/**
* 范围查询
*/
@Test
public void rangeQuery() throws Exception{
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery("age").gte(0).lte(20)));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : searchResponse.getHits().getHits()) {
Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
System.out.println(student);
}
}
18、queryString
/**
* queryString
*/
@Test
public void queryString() throws Exception{
SearchRequest searchRequest = new SearchRequest("goods");
searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.queryStringQuery("华为手机").field("title").field("categoryName").field("brandName").defaultOperator(Operator.OR)));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : searchResponse.getHits().getHits()) {
Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
System.out.println(goods);
}
}
19、布尔查询
/**
* 布尔查询
*/
@Test
public void boolQuery() throws Exception{
SearchRequest searchRequest = new SearchRequest("goods");
searchRequest.source(new SearchSourceBuilder()
.query(QueryBuilders.boolQuery()
.filter(QueryBuilders.matchQuery("title","手机"))
.filter(QueryBuilders.rangeQuery("price").gte(1000).lte(2000))));
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : searchResponse.getHits().getHits()) {
Goods goods = JSON.parseObject(hit.getSourceAsString(), Goods.class);
System.out.println(goods);
}
}
20、聚合查询
/**
* 聚合查询
*/
@Test
public void aggQuery() throws Exception{
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.source(new SearchSourceBuilder()
.aggregation(AggregationBuilders
.terms("hello_world")
.field("age").size(2)
));
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits().getHits()) {
Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
System.out.println(student);
}
}
21、高亮查询
/**
* 高亮查询
* 1. 设置高亮
* * 高亮字段
* * 前缀
* * 后缀
* 2. 将高亮了的字段数据,替换原有数据
*/
@Test
public void highLightQuery() throws Exception{
SearchRequest searchRequest = new SearchRequest("student");
searchRequest.source(new SearchSourceBuilder()
.query(QueryBuilders.matchQuery("address","江西"))//设置高亮字段
.highlighter(new HighlightBuilder()
.field("address")//高亮字段
.preTags("<font color='red'>")//前缀
.postTags("</font>")));//后缀
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : search.getHits().getHits()) {
Student student = JSON.parseObject(hit.getSourceAsString(), Student.class);
//获取高亮结果,替换student中的address
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField address = highlightFields.get("address");
Text[] fragments = address.fragments();
//替换
student.setAddress(fragments[0].toString());
System.out.println(student);
}
}