ik分词器的安装,将ik分词器下载并解压,新建文件夹ik,将解压内容放进ik文件夹中,将ik文件夹放在es安装路径的plugin文件夹中
GET _analyze
{
"analyzer": "ik_smart",
"text":"中国共产党"
}
GET _analyze
{
"analyzer": "ik_max_word",
"text":"中国共产党"
}
在es的安装目录中/elasticsearch/plugins/ik/config,创建后缀名为.dic的文件,将自己配置的词语写到.dic文件中,
文件中的内容:
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
PUT testdb //创建索引,未添加值
{
"mappings":{
"properties": {
"name":{
"type":"text"
},
"desc":{
"type":"keyword"
}
}
}
}
PUT /human/user/1
{
"name":"tfxing",
"age":18,
"desc":"优秀的中国五四好青年"
}
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" : "优秀的中国五四好青年"
}
}
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" : "优秀的中国五四好青年"
}
}
内嵌结构
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"
}
}
]
}
}
GET human/user/_search
{
"_source":["name","age"],
"sort":[
{
"age":{
"order":"asc" //按age升序排序,desc:降序
}
}
]
}
#####查询结果######
GET human/user/_search
{
"_source":["name","age"],
"sort":[
{
"age":{
"order":"asc"
}
}
],
"from":0,
"size":2
}
should(or),
GET human/user/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"age":20
}
}
]
}
}
}
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" : "优秀的中国五四好青年"
}
}
]
}
}
GET human/user/_search
{
"query":{
"bool":{
"must_not":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"age":20
}
}
]
}
}
}
GET human/user/_search
{
"query":{
"bool":{
"must":[
{
"match":{
"name":"张三"
}
}
],
"filter":{
"range":{
"age":{
"gte":22 //gt:大于、gte:大于等于、lt:小于、lte:小于等于
}
}
}
}
}
}
只要满足其一就能被查询出来
GET human/user/_search
{
"query":{
"match":{
"desc":"优秀 法外"
}
}
}
term:直接查询精确的
match:会使用分词器解析,(先分析文档,然后通过分析的文档进行查询)
GET human/user/_search
{
"query":{
"bool":{
"should":[
{
"match":{
"name":"tfxing"
}
},
{
"match":{
"name":"zxyan"
}
}
]
}
}
}
搜索相关的结果可以高亮显示
GET human/user/_search
{
"query":{
"match":{
"name":"tfxing"
}
},
"highlight":{
"pre_tags":""
, //搜索结果前缀 自定义搜索条件
"post_tags":"", //后缀
"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" : [
"tfxing
"
]
}
}
]
}
}
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>7.4.0version>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-clientartifactId>
<version>7.4.0version>
dependency>
<dependency>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
<version>7.4.0version>
dependency>
GET/_cat/nodes: 查看所有节点
GET/_cat/health: 查看es健康状况
GET/_cat/master: 查看主节点
GET/_cat/indices:查看所有索引(类似show databases)
保存一个数据,保存在那个索引的哪个类型下
PUT/customer/external/1
例:PUT http://192.168.58.20:9200/customer/external/1 { “name”:“tfxing”}
发送多次为更新,使用put和post都可以,如果不指定id,会生成一个随机id
GET customer/external
post加_update的方式会对比原来的数据,如果没有改变,则_sql_no和_version不会改变
而put和post不带_update更新不会对比原来的数据,_ sql_no和_version会改变
删除指定文档和删除整个索引(整个表)
post请求,一个大括号代表一个索引,两行为一个整体,
delete删除没有请求体,所以只有一行
create:创建,title行为创建的数据
index:保存,title行为需要保存的数据
update:更新,“_retry_on_conflict”:3:表示如果更新失败,重试3次
@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、开发流程:
<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.0modelVersion>
<artifactId>spiringbootEsartifactId>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.1.RELEASEversion>
<relativePath/>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
<version>1.16.18version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>7.4.0version>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-clientartifactId>
<version>7.4.0version>
dependency>
<dependency>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
<version>7.4.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.4version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
project>
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
集群用逗号隔开
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);
}
}
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;
}
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"
)
));
}
}
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();
}
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>
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestES {
@Autowired
private RestHighLevelClient client;
@Autowired
private GoodsMapper goodsMapper;
@Test
public void testClient(){
System.out.println(client);
}
}
/**
* 创建索引
*/
@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());
}
/**
* 添加索引和映射
*/
@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());
}
/**
* 查询索引
*/
@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());
}
}
/**
* 删除索引
*/
@Test
public void testDelete() throws Exception{
IndicesClient indices = client.indices();
AcknowledgedResponse response = indices.delete(new DeleteIndexRequest("teacher"), RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
/**
* 判断索引是否存在
*/
@Test
public void testExistIndex() throws Exception{
IndicesClient indices = client.indices();
boolean exists = indices.exists(new GetIndexRequest("person"), RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
* 添加文档,使用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());
}
/**
* 使用对象进行添加操作
* @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());
}
/**
* 修改文档
*/
@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());
}
/**
* 根据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);
}
/**
* 根据id删除文档
*/
@Test
public void delDoc() throws Exception{
DeleteResponse response = client.delete(new DeleteRequest("student", "1"), RequestOptions.DEFAULT);
System.out.println(response.status());
}
/**
*测试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);
}
}
返回结果
/**
* 测试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);
}
}
/**
* 批量操作
*/
@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());
}
/**
* 导入数据
*/
@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());
}
/**
* 使用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);
}
}
/**
* 模糊查询
*/
@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);
}
}
/**
* 范围查询
*/
@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);
}
}
/**
* 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);
}
}
/**
* 布尔查询
*/
@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);
}
}
/**
* 聚合查询
*/
@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);
}
}
/**
* 高亮查询
* 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("")//前缀
.postTags("")));//后缀
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);
}
}