<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
@Configuration
public class RestClient extends AbstractElasticsearchConfiguration {
@Value("${elasticsearch.host}")
private String host;
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration
.builder()
.connectedTo(host)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
ElasticsearchOperations
相关注解
@Data
@Document(indexName = "products", createIndex = true)
@Accessors(chain = true)
public class Product {
@Id
private Integer id;
@Field(type = FieldType.Keyword)
private String title;
@Field(type = FieldType.Double)
private Double price;
@Field(type = FieldType.Text,searchAnalyzer = "ik_max_word")
private String description;
}
新增一条文档
@Test
public void indicesTest(){
Product product = new Product()
.setId(1)
.setTitle("小浣熊干脆面")
.setPrice(2.0)
.setDescription("很好吃的小浣熊干脆面");
Product p = elasticsearchOperations.save(product);
System.out.println(p);
}
查询一条文档
@Test
public void findTest(){
Product product = elasticsearchOperations.get("1", Product.class);
System.out.println(product.getId()+product.getTitle()+product.getPrice()+product.getDescription());
}
删除一条文档
@Test
public void deleteTest(){
Product product = new Product();
product.setId(1);
String delete = elasticsearchOperations.delete(product);
System.out.println(delete);
}
删除所有文档
/**
* 删除所有文档
*/
@Test
public void deleteAllTest(){
ByQueryResponse delete = elasticsearchOperations.delete(Query.findAll(), Product.class);
System.out.println(delete);
}
查询所有文档
/**
* 查询所有文档
*/
@Test
public void findAllTest(){
SearchHits<Product> search = elasticsearchOperations.search(Query.findAll(), Product.class);
System.out.println(search.getSearchHits());
}
RestHighLevelClient
创建索引 并创建映射
@Test
public void indexAndMappingTest() throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("products");
createIndexRequest.mapping("{\n" +
" \"properties\": {\n" +
" \"title\":{\n" +
" \"type\":\"keyword\"\n" +
" },\n" +
" \"price\":{\n" +
" \"type\": \"double\"\n" +
" },\n" +
" \"create_at\":{\n" +
" \"type\": \"date\"\n" +
" },\n" +
" \"description\":{\n" +
" \"type\": \"text\",\n" +
" \"analyzer\": \"ik_max_word\"\n" +
" }\n" +
" }\n" +
" }", XContentType.JSON);
createIndexRequest.settings("{\n" +
" \"number_of_shards\": 1,\n" +
" \"number_of_replicas\": 0\n" +
" }",XContentType.JSON);
CreateIndexResponse createIndexResponse = restHighLevelClient.indices()
.create(createIndexRequest, RequestOptions.DEFAULT);
restHighLevelClient.close();//使用完记得关闭资源
}
查看是否存在索引
/**
* 判断是否存在索引
*/
@Test
public void isExistTest() throws IOException {
boolean exists = restHighLevelClient.indices().exists(new GetIndexRequest("products"), RequestOptions.DEFAULT);
System.out.println(exists);
}
删除索引
/**
* 删除索引
*/
@Test
public void indicesDeleteTest() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest();
deleteIndexRequest.indices("products");
AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices()
.delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(acknowledgedResponse.isAcknowledged());
}
索引一条文档
/**
* 索引一条文档
*/
@Test
public void indexTest() throws IOException {
IndexRequest indexRequest = new IndexRequest("products");
indexRequest.id("2").source("{\n" +
" \"title\":\"小浣熊干脆面\",\n" +
" \"price\":2.0,\n" +
" \"create_at\":\"2022-02-17\",\n" +
" \"description\":\"很好吃的小浣熊干脆面\"\n" +
"}",XContentType.JSON);
IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
}
基于id查询一条文档
/**
* 基于id查询一条文档
*/
@Test
public void findOneTest() throws IOException {
GetRequest getRequest = new GetRequest("products","1");
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse);
}
查询所有文档
/**
* 查询所有文档
*/
@Test
public void searchAllTest() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits){
System.out.println(searchHit.getId());
System.out.println(searchHit.getSourceAsString());
}
}
不同条件查询 term关键词查询
/**
* 不同条件查询 term关键词查询
*/
@Test
public void termQueryTest() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("description","浣熊"));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits){
String id = searchHit.getId();
System.out.println(id + searchHit.getSourceAsString());
}
}
其它文档查询
注意:其它文档查询将相同部分代码进行抽离
/**
* 其它查询
* @param
* @return
* @throws IOException
*/
@Test
public void otherQueryTest() throws IOException {
System.out.println("===========范围查询============");
//范围查询
query(QueryBuilders.rangeQuery("price").gt(0).lt(10));
System.out.println("===========前缀查询============");
//前缀查询
query(QueryBuilders.prefixQuery("title","小"));
System.out.println("===========通配符查询============");
//通配符查询
query(QueryBuilders.wildcardQuery("title","小浣熊*"));
System.out.println("===========ids查询============");
//ids查询 查询一组符合条件的id
query(QueryBuilders.idsQuery().addIds("1","2"));
System.out.println("===========fuzzy模糊查询============");
//fuzzy模糊查询
query(QueryBuilders.fuzzyQuery("title","小浣猫干脆面"));
System.out.println("===========bool查询============");
//bool查询
TermQueryBuilder termQueryBuilder = new TermQueryBuilder("title","日本豆");
query(QueryBuilders.boolQuery().must(termQueryBuilder).must(QueryBuilders.idsQuery().addIds("1","2")));
System.out.println("===========多字段查询============");
//multi=match多字段查询
query(QueryBuilders.multiMatchQuery("浣日","title,description"));
System.out.println("===========默认字段分词查询============");
//queryString默认字段分词查询
query(QueryBuilders.queryStringQuery("熊吃豆").defaultField("description"));
}
分页查询
/**
* 分页查询
* @return
* @throws IOException
*/
@Test
public void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery())
.from(0)
.size(1);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits){
String id = searchHit.getId();
System.out.println(id + searchHit.getSourceAsString());
}
}
排序查询
/**
* 分页查询 排序查询
* @return
* @throws IOException
*/
@Test
public void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery())
.from(0)
.size(10)
.sort("price", SortOrder.ASC);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits){
String id = searchHit.getId();
System.out.println(id + searchHit.getSourceAsString());
}
}
指定返回字段
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.matchAllQuery())
.from(0)
.size(10)
.sort("price", SortOrder.ASC)
.fetchSource(new String[]{},new String[]{"create_at"});
高亮查询
/**
* 高亮查询
* @param
* @return
* @throws IOException
*/
@Test
public void highLightTest() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("description").preTags("").postTags("");
sourceBuilder.query(QueryBuilders.termQuery("description","好吃"))
.highlighter(highlightBuilder);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits){
String id = searchHit.getId();
System.out.println(id + searchHit.getHighlightFields());
}
}
过滤查询
/**
*
* @param
* @return
* @throws IOException
*/
@Test
public void filterQueryTest() throws IOException {
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery("description","好吃"))
.postFilter(QueryBuilders.idsQuery().addIds("1").addIds("2"));//用来指定过滤条件
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit searchHit : searchHits){
String id = searchHit.getId();
System.out.println(id + searchHit.getSourceAsString());
}
}