1.pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.application.yml配置
spring:
data:
elasticsearch:
cluster-name: es6,
cluster-nodes: 192.168.174.128:9300
3.启动
3.1 启动后会报下面错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
解决
@Configuration
public class ESConfig {
/**
* 解决netty引起的issue
*/
@PostConstruct
void init(){
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
}
4.测试用例
package com.test;
import com.imooc.Application;
import com.imooc.es.pojo.Stu;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class ESTest {
@Autowired
private ElasticsearchTemplate esTemplate;
@Test
public void createIndexStu(){
Stu stu = new Stu();
stu.setStuId(1001L);
stu.setName("bat name");
stu.setAge(18);
stu.setMoney(18.8f);
stu.setSign("i am spider");
stu.setDescription("I wish i am spider man");
IndexQuery indexQuery = new IndexQueryBuilder().withObject(stu).build();
esTemplate.index(indexQuery);
}
@Test
public void deleteIndexStu(){
esTemplate.deleteIndex(Stu.class);
}
@Test
public void updateStuDoc(){
Map<String, Object> sourceMap = new HashMap<>();
sourceMap.put("sign", "I am not");
sourceMap.put("money", 88.6f);
sourceMap.put("age", 33);
IndexRequest indexRequest = new IndexRequest();
indexRequest.source(sourceMap);
UpdateQuery updateQuery = new UpdateQueryBuilder()
.withClass(Stu.class)
.withId("1001")
.withIndexRequest(indexRequest)
.build();
esTemplate.update(updateQuery);
}
@Test
public void getIndexStu(){
GetQuery query = new GetQuery();
query.setId("1001");
Stu stu = esTemplate.queryForObject(query, Stu.class);
System.out.println(stu);
}
@Test
public void deleteStuDoc(){
esTemplate.delete(Stu.class, "1001");
}
@Test
public void searchStuDoc(){
Pageable pageable = PageRequest.of(0, 10);
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("description", "spider"))
.withPageable(pageable)
.build();
AggregatedPage<Stu> pagedStu = esTemplate.queryForPage(query, Stu.class);
System.out.println("检索后的总页数" + pagedStu.getTotalPages());
List<Stu> stuList = pagedStu.getContent();
for(Stu s : stuList){
System.out.println(s);
}
}
@Test
public void highlightStuDoc(){
String preTag = "<font color='red'>";
String postTag = "</font>";
Pageable pageable = PageRequest.of(0, 10);
SortBuilder sortBuilder = new FieldSortBuilder("money")
.order(SortOrder.ASC);
SortBuilder sortBuilderAge = new FieldSortBuilder("age")
.order(SortOrder.ASC);
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("description", "spider"))
.withHighlightFields(new HighlightBuilder.Field("description")
.preTags(preTag).postTags(postTag))
.withSort(sortBuilder)
.withSort(sortBuilderAge)
.withPageable(pageable)
.build();
AggregatedPage<Stu> pagedStu = esTemplate.queryForPage(query, Stu.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable) {
List<Stu> stuListHighlight = new ArrayList<>();
SearchHits hits = response.getHits();
for(SearchHit h : hits){
HighlightField highlightField = h.getHighlightFields().get("description");
String description = highlightField.getFragments()[0].toString();
Object stuId = (Object)h.getSourceAsMap().get("stuId");
String name = (String)h.getSourceAsMap().get("name");
Integer age = (Integer)h.getSourceAsMap().get("age");
String sign = (String)h.getSourceAsMap().get("sign");
Object money = (Object)h.getSourceAsMap().get("money");
Stu stuHL = new Stu();
stuHL.setDescription(description);
stuHL.setStuId(Long.valueOf(stuId.toString()));
stuHL.setName(name);
stuHL.setAge(age);
stuHL.setSign(sign);
stuHL.setMoney(Float.valueOf(money.toString()));
stuListHighlight.add(stuHL);
}
if(stuListHighlight.size() > 0){
return new AggregatedPageImpl<>((List<T>) stuListHighlight);
}
return null;
}
});
System.out.println("检索后的总页数" + pagedStu.getTotalPages());
List<Stu> stuList = pagedStu.getContent();
for(Stu s : stuList){
System.out.println(s);
}
}
}