1、springcloud集成es,es的搭建不多说,直接配置项目,依赖,es选择版本是7.7
org.elasticsearch.client
elasticsearch-rest-high-level-client
7.7.0
org.elasticsearch
elasticsearch
org.elasticsearch.client
elasticsearch-rest-client
org.elasticsearch.client
elasticsearch-rest-client
7.7.0
org.elasticsearch
elasticsearch
7.7.0
2、配置yml
spring:
profiles:
active: dev
datasource: #配置数据库
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3307/springcloud_test002?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
redis:
host: 192.168.110.12
port: 6379
password: Cc68db0e
elasticsearch:
host: 192.168.110.12
port: 9200
username: 账号
password: 密码
3、配置类
package com.example.test002.config.elastic;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
/**
* elasticsearch 配置类
* @author admin
* @date 2022/2/10 14:03
**/
@Configuration
@Primary
public class ElasticConfig extends AbstractFactoryBean
实体
package com.example.test002.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* es实体
* @author admin
* @date 2022/2/10 14:02
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public final class ElasticEntity {
private String id;
private String _id;
private T data;
}
4、编写工具类
package com.example.test002.mapper.common;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.test002.entity.ElasticEntity;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* es工具类
* @author admin
*/
@Component
public class ElasticSearchMapper {
@Resource
private RestHighLevelClient client;
/**
* 功能描述: 创建索引
* @param index 索引名称
* @param source 配置
* @author admin
* @return boolean
* @date 2022/2/10 14:01
*/
public boolean createIndex(String index, String source) {
try {
CreateIndexRequest request = new CreateIndexRequest(index);
request.mapping(source, XContentType.JSON);
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
return createIndexResponse.isAcknowledged();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 功能描述: 判断索引是否存在
* @param index 索引名称
* @author admin
* @return boolean
* @date 2022/2/10 14:02
*/
public boolean indexExist(String index) {
try {
GetIndexRequest request = new GetIndexRequest(index);
request.local(false);
request.humanReadable(true);
request.includeDefaults(false);
return client.indices().exists(request, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 功能描述: 插入数据
* @param index 索引名称
* @param entity 数据类
* @author admin
* @return boolean
* @date 2022/2/10 14:02
*/
public boolean insertOne(String index, ElasticEntity entity) {
IndexRequest indexRequest = new IndexRequest(index);
String userJson = JSONObject.toJSONString(entity.getData());
indexRequest.source(userJson, XContentType.JSON).id(entity.get_id());
try {
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
if (indexResponse != null) {
if (indexResponse.getResult() == DocWriteResponse.Result.CREATED || indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 功能描述: 查询数据
* @param indexArray 索引数组,用于多个索引一起查询
* @param searchSourceBuilder 查询builder
* @param c 参数类型
* @author admin
* @return * @return: null
* @date 2022/2/10 14:03
* @throws Exception 异常
*/
public List listByBuilder(String[] indexArray, SearchSourceBuilder searchSourceBuilder, Class c) {
SearchRequest request = new SearchRequest(indexArray);
searchSourceBuilder.trackTotalHits(true);
request.source(searchSourceBuilder);
try {
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHit[] hits = response.getHits().getHits();
List res = new ArrayList<>(hits.length);
for (SearchHit hit : hits) {
Map sourceAsMap = hit.getSourceAsMap();
String json = JSON.toJSONString(sourceAsMap);
res.add(JSON.parseObject(json, c));
}
return res;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
5、测试
package com.example.test002.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.test002.entity.ElasticEntity;
import com.example.test002.entity.SysUserDO;
import com.example.test002.mapper.common.ElasticSearchMapper;
import com.example.test002.mapper.common.RedisMapper;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* es 测试
* @author admin
* @date 2022/2/10 9:47
*/
@RestController
@RefreshScope //nacos配置中心动态刷新
public class ElasticsearchController {
@Resource
private ElasticSearchMapper elasticSearchMapper;
/**
* 功能描述: 创建索引
* @author admin
* @return boolean
* @date 2022/2/10 13:30
*/
@GetMapping(value = "/es/createIndex")
public boolean createIndex() throws InterruptedException {
// 大致意思就是配置了四个字段,id、username、tel、rolename
// username和rolename 指定使用ik分词器,后面搜索的时候可以分词搜索
String source = "{" +
" \"properties\": {" +
" \"id\": {" +
" \"type\": \"long\"" +
" }," +
" \"username\": {" +
" \"type\": \"text\"," +
" \"analyzer\": \"ik_max_word\"," +
" \"search_analyzer\": \"ik_max_word\"" +
" }," +
" \"tel\": {" +
" \"type\": \"keyword\"" +
" }," +
" \"rolename\": {" +
" \"type\": \"text\"," +
" \"analyzer\": \"ik_max_word\"," +
" \"search_analyzer\": \"ik_max_word\"" +
" }" +
" }" +
" }";
JSONObject json = JSONObject.parseObject(source);
String s = JSONObject.toJSONString(json);
boolean index = elasticSearchMapper.createIndex("test_user", s);
return index;
}
/**
* 功能描述: 判断是否存在这个索引
* @author admin
* @return boolean
* @date 2022/2/10 14:22
*/
@GetMapping(value = "/es/indexExist")
public boolean indexExist() throws InterruptedException {
boolean index = elasticSearchMapper.indexExist("test_user");
return index;
}
/**
* 功能描述: 插入单条
* @author admin
* @return boolean
* @date 2022/2/10 14:22
*/
@GetMapping(value = "/es/insertOne")
public boolean insertOne() throws InterruptedException {
SysUserDO user = new SysUserDO();
user.setId(1);
user.setRolename("测试一下");
user.setUsername("我是测试");
user.setTel("1311111111");
ElasticEntity entity = new ElasticEntity();
entity.setData(user);
boolean index = elasticSearchMapper.insertOne("test_user", entity);
return index;
}
/**
* 功能描述: 判断是否存在这个索引
* @author admin
* @return boolean
* @date 2022/2/10 14:22
*/
@GetMapping(value = "/es/listByBuilder")
public List listByBuilder() throws InterruptedException {
// 使用分词,查询username和rolename中含有测试的
QueryBuilder nameQuery = QueryBuilders.matchQuery("username", "测试").analyzer("ik_max_word");
QueryBuilder roleQuery = QueryBuilders.matchQuery("rolename", "测试").analyzer("ik_max_word");
/*
* 组合查询
*/
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.should(nameQuery);
boolQueryBuilder.should(roleQuery);
/* 封装查询builder SearchSourceBuilder
* 开启评分
* 设置超时时间
* 分数排序
* 查询条件
*/
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.explain(true);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
sourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
sourceBuilder.query(boolQueryBuilder);
String[] indexArray = new String[]{"test_user"};
List userList = elasticSearchMapper.listByBuilder(indexArray, sourceBuilder, SysUserDO.class);
return userList;
}
}
6、启动项目,访问创建索引
查看索引情况
判断索引是否存在
插入数据
查询数据