步骤
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
}
}
ElasticSearch关于索引的API测试
@Resource
private RestHighLevelClient client;
// 测试索引的创建 : put yinrz_index
@Test
void testCreateIndex() throws IOException {
// 1.创建索引请求
CreateIndexRequest request = new CreateIndexRequest("yinrz_index");
// 2、IndicesClient索引客户端执行请求 ,请求后获得响应
IndicesClient indicesClient = client.indices();
CreateIndexResponse response = indicesClient.create(request, RequestOptions.DEFAULT);
System.out.println(response);
}
// 测试获取索引,判断其是否存在
@Test
void testGetIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("yinrz_index");
IndicesClient indicesClient = client.indices();
boolean exists = indicesClient.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
// 测试删除索引
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("yinrz_index");
IndicesClient indicesClient = client.indices();
AcknowledgedResponse response = indicesClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
ElasticSearch关于文档的API测试
@Resource
private RestHighLevelClient client;
// 测试添加文档
@Test
void testAddDocument() throws IOException {
User user = new User(1, "yinrz");
IndexRequest request = new IndexRequest("yinrz_index");
request.id("1"); // put /index_yinrz/_doc/1
request.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
System.out.println(response.status());
}
// 测试获取文档
@Test
void testGetDocument() throws IOException {
GetRequest request = new GetRequest("yinrz_index", "1");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());
System.out.println(response);
}
// 测试更新文档
@Test
void testUpdateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("yinrz_index", "1");
User user = new User(1, "yinrz2");
request.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println(response.status());
}
// 测试删除文档
@Test
void testDeleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest("yinrz_index", "1");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println(response.status());
}
// 测试批量添加数据
@Test
void testBulkDocument() throws IOException {
BulkRequest request = new BulkRequest();
ArrayList<User> list = new ArrayList<>();
list.add(new User(1, "yinrz1"));
list.add(new User(2, "yinrz2"));
list.add(new User(3, "yinrz3"));
list.add(new User(4, "yinrz4"));
list.add(new User(5, "yinrz5"));
for (int i = 0; i < list.size(); i++) {
request.add(
new IndexRequest("yinrz_index")
.id("" + (i + 1))
.source(JSON.toJSONString(list.get(i)), XContentType.JSON));
}
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.hasFailures());
}
// 测试高级搜索
@Test
void testSearch() throws IOException {
SearchRequest request = new SearchRequest("yinrz_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
// 查询全部
// MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
//精确查询
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "yinrz2");
searchSourceBuilder.query(termQueryBuilder);
request.source(searchSourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(response.getHits()));
for (SearchHit searchHit : response.getHits().getHits()) {
System.out.println(searchHit.getSourceAsMap());
}
}
实战
@Resource
HtmlParseUtil htmlParseUtil;
@Resource
RestHighLevelClient client;
// 将数据添加到ES中
public boolean addGoodsToEs(String keyword) throws Exception {
List<Goods> goods = htmlParseUtil.parseJd(keyword);
BulkRequest request = new BulkRequest();
for (int i = 0; i < goods.size(); i++) {
request.add(
new IndexRequest("jd_goods").source(JSON.toJSONString(goods.get(i)), XContentType.JSON));
}
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
return !response.hasFailures();
}
// 查询功能,支持分页,高亮
public List<Map<String, Object>> searchGoods(String keyword, int pageNo, int pageSize)
throws Exception {
SearchRequest request = new SearchRequest("jd_goods");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//分页
searchSourceBuilder.from(pageNo);
searchSourceBuilder.size(pageSize);
//高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<span style=‘color:red‘>");
highlightBuilder.postTags("</span>");
highlightBuilder.requireFieldMatch(false);
highlightBuilder.field("name");
searchSourceBuilder.highlighter(highlightBuilder);
//精确查询
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
searchSourceBuilder.query(termQueryBuilder);
request.source(searchSourceBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 解析结果
ArrayList<Map<String, Object>> list = new ArrayList<>();
for (SearchHit hit : response.getHits().getHits()) {
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField highlightField = highlightFields.get("name");
Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //原来的结果
// 解析高亮字段
if (highlightField!=null){
Text[] fragments = highlightField.getFragments();
StringBuilder name= new StringBuilder();
for (Text fragment : fragments) {
name.append(fragment);
}
sourceAsMap.put("name", name.toString()); //高亮字段替换原来的
}
list.add(sourceAsMap);
}
return list;
}
原文:https://www.cnblogs.com/yinrz/p/13152029.html