折腾了一天,终于搭出来了一个简易环境,以下内容基于ES已经安装好。
pom.xml
<!-- ES搜索引擎 -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
application.yml
木有~,原谅我没有弄出来
使用@Bean配置ES的ip和port
package org.dromara.project.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticsearchClientConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS = builder.build();
}
@Bean
public RestHighLevelClient esRestClient() {
RestHighLevelClient highLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "Http")));
return highLevelClient;
}
}
创建索引,咱起个别名(ES索引库),我总容易和MySQL的索引搞混~
代码片段:创建索引库
// ES索引库名称
String indices = "account_index";
GetIndexRequest getRequest = new GetIndexRequest(indices);
// 判断ES索引是否存在
boolean exist = client.indices().exists(getRequest, RequestOptions.DEFAULT);
if (!exist) {
// 如果不存在,创建新的索引库
CreateIndexRequest request = new CreateIndexRequest(indices);
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
log.info("创建索引库:{}", indices);
}
// 创建文档
IndexRequest request = new IndexRequest(indices).id(soleId.toString());
// 注意:此处不能直接传对象,需将对象转为JSONString
request.source(JSONObject.toJSONString(add), XContentType.JSON);
// 捕获原因,数据成功推送到ES,但仍然解析错误,网上说是boot与ES版本不匹配导致。试了多个版本,没搞定~偷个懒。
// 前提:数据成功推送到了ES
try {
// 推送数据
client.index(request, RequestOptions.DEFAULT);
} catch (IOException e) {
log.info(e.getMessage());
String msg = e.getMessage();
if(!msg.contains("201 Created") && !msg.contains("200 OK")) {
throw e;
}
简单看下这个索引库下的数据
上个代码片段执行了推送数据操作
以上是创建索引库,以及推送数据。现在开始获取数据,通常是获取id
controller层
@Resource
private ESUtils esUtils;
/**
* 根据参数获取ES索引库数据
*/
@PostMapping("/getEsList")
public R getEsList(@RequestBody Map<String,Object> params) throws IOException {
// 处理ES消息,返回id
List<String> results = esUtils.handleEsMessage((String) params.get("esIndex"), params);
return R.ok(results);
}
ES工具类
package org.dromara.project.util;
import cn.hutool.core.util.ObjectUtil;
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.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class ESUtils {
@Autowired
private RestHighLevelClient elasticsearchClient;
/**
* 处理ES消息,根据参数,获取符合条件的Id
* @param indices ES索引库
* @param params 查询参数
* @return
*/
public List<String> handleEsMessage(String indices, Map<String,Object> params) throws IOException {
SearchRequest searchRequest = new SearchRequest(indices);
// 构造条件
SearchSourceBuilder builder = new SearchSourceBuilder();
List<Map<String,Object>> paramMapList = (List<Map<String, Object>>) params.get("params");
// 查询条件存储List
List<QueryBuilder> termQueryBuilderList = new ArrayList<>();
for (Map<String, Object> map : paramMapList) {
String eq = (String) map.get("eq");
if (eq.equals("=")) {
// 精确匹配
QueryBuilder queryBuilder = QueryBuilders.termQuery((String) map.get("name"),map.get("value"));
termQueryBuilderList.add(queryBuilder);
}
if (eq.equals("like")) {
// 模糊匹配
QueryBuilder queryBuilder = QueryBuilders.fuzzyQuery((String) map.get("name"),map.get("value"));
termQueryBuilderList.add(queryBuilder);
}
if (eq.equals("<")) {
// 小于
QueryBuilder queryBuilder = QueryBuilders.rangeQuery((String) map.get("name")).lt(map.get("value"));
termQueryBuilderList.add(queryBuilder);
}
if (eq.equals("<=")) {
// 小于等于
QueryBuilder queryBuilder = QueryBuilders.rangeQuery((String) map.get("name")).lte(map.get("value"));
termQueryBuilderList.add(queryBuilder);
}
if (eq.equals(">")) {
// 大于
QueryBuilder queryBuilder = QueryBuilders.rangeQuery((String) map.get("name")).gt(map.get("value"));
termQueryBuilderList.add(queryBuilder);
}
if (eq.equals(">=")) {
// 大于等于
QueryBuilder queryBuilder = QueryBuilders.rangeQuery((String) map.get("name")).gte(map.get("value"));
termQueryBuilderList.add(queryBuilder);
}
}
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
for (QueryBuilder item : termQueryBuilderList) {
boolQueryBuilder.must(item);
}
// 匹配全部 matchAllQuery();
builder.query(boolQueryBuilder);
// 分页
builder.from(ObjectUtil.isEmpty(params.get("page"))? 0: Integer.parseInt(String.valueOf(params.get("page"))));
builder.size(ObjectUtil.isEmpty(params.get("size"))? 10: Integer.parseInt(String.valueOf(params.get("size"))));
// builder.size(10);
builder.timeout(TimeValue.MINUS_ONE);
searchRequest.source(builder);
SearchResponse response = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
List<String> results = new ArrayList<>();
for (org.elasticsearch.search.SearchHit hit : response.getHits().getHits()) {
hit.getSourceAsMap().get("name");
// 获取对象的Id
// results.add((String) hit.getSourceAsMap().get("id"));
// 存入ES,主动设置Id,保证对象的Id和ES的Id一致,这样取ES的Id即可
results.add(hit.getId());
}
return results;
}
}