看了下,目前阿里云推荐的ES版本是7.10.0,SpringData的最新版本,只支持到ES的7.15.2
但是之前我安装的时候使用了7.17.0
那么为了更优雅地处理ES的增删改查,我还是决定把版本降到7.15.2(貌似就无法使用 ES JAVA Client 了,但相比起引入了SpringDataElasticsearch来说,感觉还是很能接受的)
这里先做一个入门
spring: elasticsearch: # 多节点逗号隔开 uris: http://127.0.0.1:9200
代码POJO类
package com.example.es01.pojo;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.springframework.data.annotation.Id;import org.springframework.data.elasticsearch.annotations.document;import org.springframework.data.elasticsearch.annotations.Field;import org.springframework.data.elasticsearch.annotations.FieldType;@Data@NoArgsConstructor@AllArgsConstructor@document(indexName = "product")public class Product {@Idprivate Integer id;@Field(type = FieldType.Text)private String name;@Field(type = FieldType.Long)private Long price;}
DAO
package com.example.es01.dao;import com.example.es01.pojo.Product;import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;public interface ProductRepository extends ElasticsearchRepository
单元测试
package com.example.es01;import com.alibaba.fastjson.JSON;import com.example.es01.dao.ProductRepository;import com.example.es01.pojo.Product;import org.elasticsearch.index.query.BoolQueryBuilder;import org.elasticsearch.index.query.QueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.elasticsearch.index.query.TermQueryBuilder;import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;import org.elasticsearch.search.sort.SortBuilders;import org.elasticsearch.search.sort.SortOrder;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.domain.PageRequest;import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;import org.springframework.data.elasticsearch.core.SearchHit;import org.springframework.data.elasticsearch.core.SearchHits;import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;import org.springframework.data.elasticsearch.core.query.Query;import java.util.ArrayList;import java.util.List;import java.util.stream.Stream;@SpringBootTestclass Es01ApplicationTests {@AutowiredProductRepository productRepository;@AutowiredElasticsearchRestTemplate elasticsearchRestTemplate;@Testvoid testCreateIndex(){boolean b = elasticsearchRestTemplate.indexOps(Product.class).create();System.out.println(b);}@Testvoid saveProduct(){Product product = elasticsearchRestTemplate.save(new Product(1, "小苹果", 100L));System.out.println(JSON.toJSONString(product));}@Testvoid queryProduc(){NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("name", "小苹果")).build();SearchHits