Spring Boot 2.6.3 、Elasticsearch6.6.2、 JDK1.8
依赖POMapplication.yml配置1.8 6.4.3 org.projectlombok lombok1.18.4 com.alibaba fastjson1.2.59 junit junittest org.elasticsearch elasticsearch${elasticSearch.version} org.elasticsearch.client transport${elasticSearch.version} org.elasticsearch.client elasticsearch-rest-high-level-client${elasticSearch.version} org.elasticsearch.plugin transport-netty4-client${elasticSearch.version}
elasticsearch: cluster-name: test-es # 多台机器用,分割 cluster-nodes: 192.168.116.200:9300ESConfig 配置类
package com.example.link.config;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
@Configuration
@Slf4j
public class ESConfig {
private static final String CLUSTER_NODES_SPLIT_SYMBOL = ",";
private static final String HOST_PORT_SPLIT_SYMBOL = ":";
@Value("${elasticsearch.cluster-name}")
String clusterName;
@Value("${elasticsearch.cluster-nodes}")
String clusterNodes;
@Bean
public TransportClient getTransportClient() {
log.info("elasticsearch init.");
if (StringUtils.isEmpty(clusterName)) {
throw new RuntimeException("elasticsearch.cluster-name is empty.");
}
if (StringUtils.isEmpty(clusterNodes)) {
throw new RuntimeException("elasticsearch.cluster-nodes is empty.");
}
try {
Settings settings = Settings.builder().put("cluster.name", clusterName.trim())
.put("client.transport.sniff", true).build();
TransportClient transportClient = new PreBuiltTransportClient(settings);
String[] clusterNodeArray = clusterNodes.trim().split(CLUSTER_NODES_SPLIT_SYMBOL);
for (String clusterNode : clusterNodeArray) {
String[] clusterNodeInfoArray = clusterNode.trim().split(HOST_PORT_SPLIT_SYMBOL);
TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(clusterNodeInfoArray[0]),
Integer.parseInt(clusterNodeInfoArray[1]));
transportClient.addTransportAddress(transportAddress);
}
log.info("elasticsearch init success.");
return transportClient;
} catch (Exception e) {
throw new RuntimeException("elasticsearch init fail.");
}
}
}
linkWebAApplicationTests 测试类
package com.example.link;
import com.alibaba.fastjson.JSON;
import com.example.link.domain.Student;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
class linkWebAApplicationTests {
private Student student;
@Autowired
private TransportClient transportClient;
@Test
void test() {
student = new Student();
student.setName("test2");
student.setAge(20);
IndexResponse response = transportClient.prepareIndex("school","student","1").setSource(JSON.toJSonString(student), XContentType.JSON)
.get();
log.info("status:{}",response.status().getStatus());
}
@Test
void test2() {
student = new Student();
student.setName("test2");
student.setAge(20);
IndexResponse response = transportClient.prepareIndex("school","student").setSource(JSON.toJSonString(student), XContentType.JSON)
.get();
log.info("status:{}",response.status().getStatus());
}
@Test
void test3() {
//建立批量提交类
BulkRequestBuilder bulkRequest =transportClient.prepareBulk();
for (int i = 0; i<= 10 ;i++){
student = new Student();
student.setName("lx"+i);
student.setAge(i);
bulkRequest.add(transportClient.prepareIndex("school","student").setSource(JSON.toJSonString(student), XContentType.JSON));
}
BulkResponse bulkResponse=bulkRequest.execute().actionGet();
//提交过程是否产生错误
if(bulkResponse.hasFailures()){
log.info("buildFailureMessage:{}",bulkResponse.buildFailureMessage());
}else {
log.info("bulkRequest success !");
}
}
@Test
void test4(){
SearchRequestBuilder builder = transportClient.prepareSearch("school");
builder.setTypes("student");
builder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
builder.setFrom(0);
builder.setSize(20);
//explain为true表示根据数据相关度排序,和关键字匹配最高的排在前面
builder.setExplain(true);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
// 搜索 name 字段包含test2的数据
queryBuilder.must(QueryBuilders.matchQuery("name", "lx0"));
queryBuilder.must(QueryBuilders.matchQuery("age", "0"));
//多个字段查询一个文本
queryBuilder.must(QueryBuilders.multiMatchQuery("0", "name","age"));
// 多条件查询 FunctionScore
FunctionScoreQueryBuilder query = QueryBuilders.functionScoreQuery(queryBuilder);
builder.setQuery(query);
SearchResponse response = builder.execute().actionGet();
SearchHits hits = response.getHits();
List



