RestHighLevelClient和ES之间的交互都是以json格式进行的。比如我们往ES中存入的数据和从ES查询出来的数据都是json格式。
但是我们的Java是面向对象的,我们如何处理?
很简单,只需要通过调用API将对象序列化成json/json反序列化成对象即可
@SpringBootTest
public class RestHighLevelClientForObjectTest {
private RestHighLevelClient restHighLevelClient;
@Autowired
public RestHighLevelClientForObjectTest(RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
/*
将数据放入es中
*/
@Test
public void testAdd() throws IOException {
Product product = new Product();
product.setId(1);
product.setTitle("小浣熊");
product.setPrice(1.5);
product.setDescription("小浣熊真好吃");
//录入es中
IndexRequest indexRequest = new IndexRequest("products");
indexRequest.id(product.getId().toString())//指定_id
.source(new ObjectMapper().writeValueAsString(product), XContentType.JSON);//调用springboot的api中方法将对象转化为json格式
IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index.status());
}
/*
查询数据:封装到对象中去
*/
@Test
public void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
HighlightBuilder highlightBuilder = new HighlightBuilder();//高亮器
highlightBuilder.requireFieldMatch(false).field("description").preTags("<span style='color:red;'>").postTags("</span>");
sourceBuilder.query(QueryBuilders.termQuery("description", "好吃"))
.from(0)
.size(10)
.highlighter(highlightBuilder);
searchRequest.source(sourceBuilder);
SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = search.getHits().getHits();
List<Product> productList = new ArrayList<>();
for (SearchHit hit : hits) {
Product product = new Product();
product = new ObjectMapper().readValue(hit.getSourceAsString(), Product.class);//将json格式转化为对象
//处理高亮 因为高亮不会改变原始数据,所以我们需要处理
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if (highlightFields.containsKey("description")){
product.setDescription(highlightFields.get("description").fragments()[0].toString());
}
productList.add(product);
}
for (Product product : productList) {
System.out.println(product);
}
}
}