Elasticsearch使用(4):springboot操作es
1 添加es
1.1 在项目中添加依赖
保持与项目中的spingboot版本一致。
<!-- springboot操作ES包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
1.2 编写es配置类
application.yml中添加es连接
es:
host: 192.168.197.131
port: 9200
username: elastic
# password:
es配置类
package com.ywz.framework.es;
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.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class EsConfig {
@Value("${es.host}")
private String host;
@Value("${es.port}")
private int port;
@Value("${es.username}")
private String username;
private String password;
@Bean
public RestHighLevelClient client() {
//初始化ES操作客户端
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//es账号密码(默认用户名为elastic,密码null)
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
return new RestHighLevelClient(
RestClient.builder(
new HttpHost(host, port)
).setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
})
);
}
}
- BasicCredentialsProvider:基本的es认证类,提供了账号密码认证。
- RestHighLevelClient:es客户端组件,其封装系统操作ES的方法,包括索引结构管理,数据增删改查管理,常用查询方法,并且可以结合原生ES查询原生语法,功能十分强大。
1.3 测试
编写测试代码
@SpringBootTest
public class EsTest {
@Resource
private RestHighLevelClient client;
@Test
public void test() throws IOException {
GetRequest getRequest = new GetRequest("test","0HsQqZMBEAxOTDxx00tZ");
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(response);
}
}
运行程序测试,上面是一个安全警告,下面是搜索的内容。
2 索引管理
2.1 判断索引是否存在
@Test
public void indexTest() throws IOException {
boolean test = client.indices().exists(new GetIndexRequest("test"), RequestOptions.DEFAULT);
System.out.println("test索引是否存在:" + test);
}
2.2 创建索引
创建索引之前需要先验证索引是否存在。
@Test
public void indexTest() throws IOException {
// 索引属性
Map<String, Object> columnMap = new HashMap<>();
// 名字
Map<String, Object> nameMap = new HashMap<>();
nameMap.put("type", "keyword");
columnMap.put("name", nameMap);
// 年龄
Map<String, Object> ageMap = new HashMap<>();
ageMap.put("type", "integer");
columnMap.put("age", ageMap);
// 信息
Map<String, Object> infoMap = new HashMap<>();
infoMap.put("analyzer", "ik_smart");
infoMap.put("type", "text");
columnMap.put("info", infoMap);
// 创建索引
CreateIndexRequest request = new CreateIndexRequest("test2");
Map<String, Object> source = new HashMap<>();
source.put("properties", columnMap);
request.mapping(source);
client.indices().create(request, RequestOptions.DEFAULT);
}
2.3 删除索引
删除索引之前需要验证索引是否存在,否则会抛出异常。
@Test
public void indexTest() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("test2");
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
3 数据管理
这里在更新数据时,可以直接修改索引结构,在dataMap中放进新的字段即可。
3.1 写入
@Test
public void insert(String indexName, Map<String, Object> dataMap) throws IOException {
BulkRequest request = new BulkRequest();
request.add(new IndexRequest(indexName).id(dataMap.remove("id").toString())
.opType("create").source(dataMap, XContentType.JSON));
client.bulk(request, RequestOptions.DEFAULT);
}
3.2 批量写入
@Test
public void batchInsert(String indexName, List<Map<String, Object>> userIndexList) throws IOException {
BulkRequest request = new BulkRequest();
for (Map<String, Object> dataMap : userIndexList) {
request.add(new IndexRequest(indexName).id(dataMap.remove("id").toString())
.opType("create").source(dataMap, XContentType.JSON));
}
client.bulk(request, RequestOptions.DEFAULT);
}
3.3 更新
@Test
public void update(String indexName, Map<String, Object> dataMap) throws IOException {
UpdateRequest updateRequest = new UpdateRequest(indexName, dataMap.remove("id").toString());
updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
updateRequest.doc(dataMap);
client.update(updateRequest, RequestOptions.DEFAULT);
}
3.4 删除
@Test
public void delete(String indexName, String id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
client.delete(deleteRequest, RequestOptions.DEFAULT);
}
4 查询操作
查询总数的CountRequest语法,SearchRequest查询结果中数据转换语法,分页查询中需要指定偏移位置和分页大小。
4.1 查询条数
@Test
public void count(String indexName) throws IOException {
// 指定创建时间
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("createTime", 1611378102795L));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(queryBuilder);
CountRequest countRequest = new CountRequest(indexName);
countRequest.source(sourceBuilder);
CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
System.out.println(countResponse.getCount());
}
4.2 查询集合
@Test
public void list(String indexName) throws IOException {
// 查询条件,指定时间并过滤指定字段值
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.termQuery("createTime", 1611378102795L));
queryBuilder.mustNot(QueryBuilders.termQuery("name", "北京-李四"));
sourceBuilder.query(queryBuilder);
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.source(sourceBuilder);
SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
List<Map<String, Object>> data = new ArrayList<>();
SearchHit[] searchHitArr = searchResp.getHits().getHits();
for (SearchHit searchHit : searchHitArr) {
Map<String, Object> temp = searchHit.getSourceAsMap();
temp.put("id", searchHit.getId());
data.add(temp);
}
System.out.println(data);
}
4.3 分页查询
@Test
public void page(String indexName, Integer offset, Integer size) throws IOException {
// 查询条件,指定时间并过滤指定字段值
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(offset);
sourceBuilder.size(size);
sourceBuilder.sort("createTime", SortOrder.DESC);
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.source(sourceBuilder);
SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
List<Map<String, Object>> data = new ArrayList<>();
SearchHit[] searchHitArr = searchResp.getHits().getHits();
for (SearchHit searchHit : searchHitArr) {
Map<String, Object> temp = searchHit.getSourceAsMap();
temp.put("id", searchHit.getId());
data.add(temp);
}
}
5 排序方式
排序除了常规的指定字段升序降序规则之外,还可以基于原生的脚本语法,基于自定义规则排序让一些特定的数据沉底或者置顶。
5.1 排序规则
@Test
public void sort(String indexName) throws IOException {
// 先升序时间,在倒序年龄
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.sort("createTime", SortOrder.ASC);
sourceBuilder.sort("age", SortOrder.DESC);
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.source(sourceBuilder);
SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
List<Map<String, Object>> data = new ArrayList<>();
SearchHit[] searchHitArr = searchResp.getHits().getHits();
for (SearchHit searchHit : searchHitArr) {
Map<String, Object> temp = searchHit.getSourceAsMap();
temp.put("id", searchHit.getId());
data.add(temp);
}
}
5.2 自定义排序规则
@Test
public void defSort(String indexName) throws IOException {
// 指定置换顺序的规则
// [age 12-->60]\[age 19-->10]\[age 13-->30]\[age 18-->40],age其他值忽略为1
Script script = new Script("def _ageSort = doc['age'].value == 12?60:" +
"(doc['age'].value == 19?10:" +
"(doc['age'].value == 13?30:" +
"(doc['age'].value == 18?40:1)));" + "_ageSort;");
ScriptSortBuilder sortBuilder = SortBuilders.scriptSort(script, ScriptSortBuilder.ScriptSortType.NUMBER);
sortBuilder.order(SortOrder.ASC);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.sort(sortBuilder);
SearchRequest searchRequest = new SearchRequest(indexName);
searchRequest.source(sourceBuilder);
SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
List<Map<String, Object>> data = new ArrayList<>();
SearchHit[] searchHitArr = searchResp.getHits().getHits();
for (SearchHit searchHit : searchHitArr) {
Map<String, Object> temp = searchHit.getSourceAsMap();
temp.put("id", searchHit.getId());
data.add(temp);
}
}
原文地址:https://blog.csdn.net/qq_40298351/article/details/144367436
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!