產(chǎn)品經(jīng)理做網(wǎng)站網(wǎng)站頁(yè)面
簡(jiǎn)介
Spring Data for Elasticsearch 是 Spring Data 項(xiàng)目的一部分,該項(xiàng)目旨在為新數(shù)據(jù)存儲(chǔ)提供熟悉且一致的基于 Spring 的編程模型,同時(shí)保留特定于存儲(chǔ)的特性和功能。
Spring Data Elasticsearch 項(xiàng)目提供了與 Elasticsearch 搜索引擎的集成。Spring Data Elasticsearch 的關(guān)鍵功能領(lǐng)域是以 POJO 為中心的模型,用于與 Elastichsearch 文檔交互并輕松編寫存儲(chǔ)庫(kù)樣式的數(shù)據(jù)訪問層。
簡(jiǎn)單使用
1.創(chuàng)建SpringBoot項(xiàng)目,導(dǎo)入Spring Data Elasticsearch的起步依賴。
/*elasticsearch的起步依賴*/
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>/*lomobok起步依賴*/<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
2.編寫配置文件,連接ElasticSearch
spring:elasticsearch:uris: https://192.168.66.101:9200username: elasticpassword: 12345678
?打印日志?
logging: pattern: console: '%d{HH:mm:ss.SSS} %clr(%-5level) --- [%-15thread] %cyan(%-50logger{50}):%msg%n'
從 ES8 開始,訪問 ES 的協(xié)議從 http 變成了 https ,訪問 https 請(qǐng)求 需要SSL 證書,在開發(fā)環(huán)境下我們不需要配置該證書,在項(xiàng)目中 添加一個(gè)配置類,跳過SSL 證書檢查即可。
3.創(chuàng)建配置類跳過SSL證書檢查?
@Component
public class RestClientBuilderCustomizerImpl implements RestClientBuilderCustomizer {@Overridepublic void customize(RestClientBuilder builder) {}/*** 跳過SSL的證書檢查*/@Overridepublic void customize(HttpAsyncClientBuilder builder) {SSLContextBuilder sscb = SSLContexts.custom();try {sscb.loadTrustMaterial((chain, authType) -> {return true;});} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);} catch (KeyStoreException e) {throw new RuntimeException(e);}try {builder.setSSLContext(sscb.build());} catch (KeyManagementException | NoSuchAlgorithmException e) {e.printStackTrace();}}
}
?4.創(chuàng)建實(shí)體類
一個(gè)實(shí)體類的所有對(duì)象都會(huì)存入 ES 的一個(gè)索引中,所以我們?cè)趧?chuàng)建實(shí)體類時(shí)關(guān)聯(lián)ES 索引
@Document(indexName = "product",createIndex = true) //關(guān)聯(lián)名為product的索引
@Data
@AllArgsConstructor
public class Product {@Id //標(biāo)記在成員變量上,標(biāo)記一個(gè)字段為主鍵,該字段的值會(huì)同步到ES該文檔的id值//標(biāo)記在成員變量上,標(biāo)記為文檔中的域,一般有如下屬性->// type域的類型,index是否創(chuàng)建索引,store是否單獨(dú)存儲(chǔ),analyzer分詞器,searchAnalyzer搜索分詞器@Field(type = FieldType.Integer,store = true,index = true)private Integer id;@Field(type = FieldType.Text,store = true,index = true,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")private String productName;@Field(type = FieldType.Text,store = true,index = true,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")private String productDesc;
}
?5.創(chuàng)建Repository接口
Repository 接口繼承 ElasticsearchRepository, 該接口提供了文檔的增刪改查方法
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {
}
6.測(cè)試Repository接口
6.1測(cè)試保存和修改方法
@SpringBootTest
public class ProductRepositoryTest {@Autowiredprivate ProductRepository repository;//保存文檔public void addProduct(){Product product = new Product(1, "今天是第一天", "第一天plus");repository.save(product);}//修改方法(當(dāng)該文檔已經(jīng)存在,即對(duì)其進(jìn)行修改)public void addProduct(){Product product = new Product(1, "今天是第first天", "第first天plus");repository.save(product);}
}
6.2查找文檔方法
6.2.1根據(jù)id進(jìn)行查詢
@Testpublic void findById(){Optional<Product> byId = repository.findById(1);System.out.println(byId.get());}
6.2.2查詢所有文檔
@Testpublic void findAll(){repository.findAll().forEach(System.out::println);}
6.3測(cè)試刪除方法
//根據(jù)其主鍵id進(jìn)行刪除
@Testpublic void deleteById(){repository.deleteById(1);}
7.使用DSL語(yǔ)句查詢文檔
query 后的 json 對(duì)象稱為 DSL語(yǔ)句 ,我們可以在接口方法上使用 @Query注解自定義 DSL 語(yǔ)句查詢。
?在Repository接口層編寫方法
7.1 匹配查詢
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {//匹配查詢@Query("{\n" +" \"match\": {\n" +" \"productDesc\": \"?0\"\n" +" }\n" +" }")List<Product> findByProductDescMatch(String keyword);
}
7.2模糊查詢
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {@Query(" {\n" +" \"match\": {\n" +" \"productDesc\":{\n" +" \"query\": \"\\?0\",\n" +" \"fuzziness\": 1\n" +" }\n" +" }\n" +" }")List<Product> findByProductDescFuzzy(String keyword);
}
8.按照規(guī)則命名方法查詢文檔
?1.只需在 Repository 接口中按照一定的規(guī)則命名方法,該方法就能完成相應(yīng)的查詢
2. 規(guī)則:查詢方法以 findBy 開頭,涉及查詢條件時(shí),條件的屬性用條件關(guān)鍵字連接。
8.1單條件查詢
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {//根據(jù)規(guī)則進(jìn)行查詢-通過productNameList<Product> findByProductName(String productName);
}
測(cè)試:
@Testpublic void testFindByProductName(){List<Product> byProductName = repository.findByProductName("iphone");byProductName.forEach(System.out::println);}
8.2 多條件選擇查詢
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {
//測(cè)試按照規(guī)則命名使用 Or 查詢
List<Product> findByProductNameOrProductDesc(String productName,String productDesc);
}
測(cè)試:
@Testpublic void testFindByProductNameOrProductDesc(){repository.findByProductNameOrProductDesc("iphone","三體").forEach(System.out::println);}
8.3范圍查詢
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {//測(cè)試使用命名規(guī)則進(jìn)行 范圍查詢
List<Product> findByIdBetween(Integer start,Integer end);
}
測(cè)試:
@Testpublic void testFindByProductIdBetween(){repository.findByIdBetween(1,3).forEach(System.out::println);}
9.分頁(yè)查詢
在使用繼承或自定義的方法時(shí),在方法中添加 Pageable 類型的參 數(shù),返回值為Page 類型即可進(jìn)行分頁(yè)查詢。
9.1繼承方法
@Testpublic void testFindPage(){//參數(shù)1:當(dāng)前頁(yè),從0開始,參數(shù)2:每頁(yè)顯示多少條Pageable pageable = PageRequest.of(0,3);Page<Product> all = repository.findAll(pageable);System.out.println("總條數(shù):"+all.getTotalElements());System.out.println("總頁(yè)數(shù):"+all.getTotalPages());System.out.println("數(shù)據(jù):"+all.getContent());}
10.分頁(yè)查詢并排序
10.1繼承方法
使用繼承或自定義的方法時(shí),在方法中添加 Sort 類型的參數(shù)即可進(jìn)行結(jié)果排序。
@Testpublic void testFindPage2(){//既分頁(yè),又排序Sort sort = Sort.by(Sort.Direction.DESC, "id");Pageable pageable = PageRequest.of(0,3,sort);Page<Product> all = repository.findByProductDescMatch("體",pageable);System.out.println("總條數(shù):"+all.getTotalElements());System.out.println("總頁(yè)數(shù):"+all.getTotalPages());System.out.println("數(shù)據(jù):"+all.getContent());}