*
package com.coolman.hotel.test;
import com.coolman.hotel.pojo.HotelDoc;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.lucene.search.TotalHits;
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.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class FullTextSearchDemo {
// 注入 RestHighLevelClient对象
@Autowired
private RestHighLevelClient restHighLevelClient;
// jackson
private final ObjectMapper objectMapper = new ObjectMapper();
/**
* 查询所有测试
*/
@Test
public void testMatchAll() throws IOException {
// 1. 创建一个查询请求对象
SearchRequest searchRequest = new SearchRequest("hotel"); // 指定索引
// 2. 添加查询的类型
MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
searchRequest.source().query(matchAllQueryBuilder); // source就相当于{}
searchRequest.source().size(100); // RestAPI默认返回的是10条数据,可以更改size的属性,即可自定义返回的数据量
// 3. 发出查询的请求,得到响应结果
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 4. 处理响应的结果
handlerResponse(response);
}
/**
* 用来处理响应数据(相当于解析返回的JSON数据)
* @param response
*/
private void handlerResponse(SearchResponse response) throws JsonProcessingException {
// 1. 得到命中的数量(即总记录数量)
SearchHits hits = response.getHits();
long totalCount = hits.getTotalHits().value;// 总记录数
System.out.println("总记录数量为:" + totalCount);
// 2. 获取本次查询出来的列表数据
SearchHit[] hitsArray = hits.getHits();
for (SearchHit hit : hitsArray) {
// 得到json字符串
String json = hit.getSourceAsString();
// 将json字符串转换为实体类对象
HotelDoc hotelDoc = objectMapper.readValue(json, HotelDoc.class);
System.out.println(hotelDoc);
}
}
} ~~~
Original: https://www.cnblogs.com/OnlyOnYourself-lzw/p/16570714.html
Author: OnlyOnYourself-Lzw
Title: 05-ElasticSearch高级搜索
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/581571/
转载文章受原作者版权保护。转载请注明原作者出处!