1. 数据库脚本
DROP TABLE IF EXISTS `tb_hotel`;
CREATE TABLE `tb_hotel` (`id` bigint(0) NOT NULL,`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT '' COMMENT '酒店名称',`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '酒店地址',`price` int(0) NOT NULL COMMENT '价格',`score` int(0) NOT NULL COMMENT '酒店评分',`brand` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '酒店品牌',`city` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '所在城市',`star_name` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '酒店星级',`business` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '商圈',`latitude` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '维度',`longitude` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '精度',`pic` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '酒店图片',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1;
2. mappings的定义
put /hotel
{"mappings":{"properties":{//id需要进行crud操作,但是不需要分词"id":{"type":"keyword"},//需要进行检索,也需要进行分词"name":{"type":"text","analyzer":"ik_max_word","copy_to":"all"},//地址不需要检索"address":{"type":"keyword","index":false},//需要参与检索"price":{"type":"integer"},//需要参与检索"score":{"type":"integer"},//需要参与检索"brand":{"type":"keyword","copy_to":"all"},"city":{"type":"keyword"},"starName":{"type":"keyword"},"business":{"type":"keyword","copy_to":"all"},//需要参与检索,地理信息类型的数据"location":{"type":"geo_point"},"pic":{"type":"keyword","index":false},"all":{"type":"text","analyzer":"ik_max_word"}}}
}
3. 初始化客户端
引入依赖
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>6.8.2</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>6.8.2</version></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>6.8.2</version></dependency>
yml配置
elasticsearch:schema: httpaddress: 127.0.0.1:9200connectTimeout: 10000socketTimeout: 10000connectionRequestTimeout: 10000maxConnectNum: 100maxConnectPerRoute: 100
初始化客户端
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.ArrayList;
import java.util.List;
/*** ElasticSearch 配置*/
@Configuration
@SuppressWarnings("all")
public class ElasticSearchConfig {/** 协议 */@Value("${elasticsearch.schema:http}")private String schema;/** 集群地址,如果有多个用“,”隔开 */@Value("${elasticsearch.address}")private String address;/** 连接超时时间 */@Value("${elasticsearch.connectTimeout:5000}")private int connectTimeout;/** Socket 连接超时时间 */@Value("${elasticsearch.socketTimeout:10000}")private int socketTimeout;/** 获取连接的超时时间 */@Value("${elasticsearch.connectionRequestTimeout:5000}")private int connectionRequestTimeout;/** 最大连接数 */@Value("${elasticsearch.maxConnectNum:100}")private int maxConnectNum;/** 最大路由连接数 */@Value("${elasticsearch.maxConnectPerRoute:100}")private int maxConnectPerRoute;public static final RequestOptions COMMON_OPTIONS;static {RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();COMMON_OPTIONS = builder.build();}@Beanpublic RestHighLevelClient restHighLevelClient() {// 拆分地址List<HttpHost> hostLists = new ArrayList<>();String[] hostList = address.split(",");for (String addr : hostList) {String host = addr.split(":")[0];String port = addr.split(":")[1];hostLists.add(new HttpHost(host, Integer.parseInt(port), schema));}// 转换成 HttpHost 数组HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});// 构建连接对象RestClientBuilder builder = RestClient.builder(httpHost);// 异步连接延时配置builder.setRequestConfigCallback(requestConfigBuilder -> {requestConfigBuilder.setConnectTimeout(connectTimeout);requestConfigBuilder.setSocketTimeout(socketTimeout);requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);return requestConfigBuilder;});// 异步连接数配置builder.setHttpClientConfigCallback(httpClientBuilder -> {httpClientBuilder.setMaxConnTotal(maxConnectNum);httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);return httpClientBuilder;});return new RestHighLevelClient(builder);}
}
引入客户端对象进行使用
@Autowired
private RestHighLevelClient restHighLevelClient;
4 创建索引库
private static final String hotelDSL = "{\n" +" \"mappings\":{\n" +" \"properties\":{\n" +" \"id\":{\n" +" \"type\":\"keyword\"\n" +" },\n" +" \"name\":{\n" +" \"type\":\"text\",\n" +" \"analyzer\":\"ik_max_word\",\n" +" \"copy_to\":\"all\"\n" +" },\n" +" \"address\":{\n" +" \"type\":\"keyword\",\n" +" \"index\":false\n" +" },\n" +" \"price\":{\n" +" \"type\":\"integer\"\n" +" },\n" +" \"score\":{\n" +" \"type\":\"integer\"\n" +" },\n" +" \"brand\":{\n" +" \"type\":\"keyword\",\n" +" \"copy_to\":\"all\"\n" +" },\n" +" \"city\":{\n" +" \"type\":\"keyword\"\n" +" },\n" +" \"starName\":{\n" +" \"type\":\"keyword\"\n" +" },\n" +" \"business\":{\n" +" \"type\":\"keyword\",\n" +" \"copy_to\":\"all\"\n" +" },\n" +" \"location\":{\n" +" \"type\":\"geo_point\"\n" +" },\n" +" \"pic\":{\n" +" \"type\":\"keyword\",\n" +" \"index\":false\n" +" },\n" +" \"all\":{\n" +" \"type\":\"text\",\n" +" \"analyzer\":\"ik_max_word\"\n" +" }\n" +" }\n" +" }\n" +"}";@Autowiredprivate RestHighLevelClient restHighLevelClient;@GetMapping("createIndex")public void createIndex() throws IOException {//1.创建request对象CreateIndexRequest request = new CreateIndexRequest("hotel");//2. 准备请求的DSL语句request.source(hotelDSL, XContentType.JSON);//3.发送请求,创建索引库restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);}
查询创建结果:
get /hotel
5. 删除索引库
//删除索引库@GetMapping("delIndex")public void delIndex() throws IOException {//1.创建request对象DeleteIndexRequest request = new DeleteIndexRequest("hotel");//3.发送请求,创建索引库restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);}
6 判断索引是否存在
//判断索引库是否存在@GetMapping("existIndex")public boolean existIndex() throws IOException {GetIndexRequest request = new GetIndexRequest("hotel");boolean exist = restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);return exist;}