一宝鼓、實體(Entity)
@Document(indexName = "my_index", type = "newsEntity",shards = 1, replicas = 0, refreshInterval = "-1")
//Document :每一條記錄就是一篇文檔
//indexName :文檔的索引名稱--唯一標記
//type :文檔類型 doc ppt xls story product
//shards : 數(shù)據(jù)分片個數(shù) 默認將數(shù)據(jù)存6份,5個主份+1個備份
public class NewsEntityextends BaseModel {
//編號id 主鍵
? ??@Id
? ? String id;
//type : Text表示文本,可被分詞也可被索引;Keyword表示關鍵字,不分詞可被索引,但String被分詞
//index : true表示可被索引;false表示不可被索引
//store : true表示可被儲存;alse表示不可被儲存
//analyzer : 執(zhí)行分詞器
? ? @Field(type = FieldType.Text, analyzer ="ik_max_word")
Stringtitle;
? ? @Field(type = FieldType.Text, analyzer ="ik_max_word")
Stringcontent;
二烙懦、源碼解釋
(1)@Document
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {
StringindexName(); //索引名稱
? ? Stringtype()default "";//文檔類型
? ? boolean useServerConfiguration()default false;//是否使用服務配置
? ? short shards()default 5;//默認分區(qū)數(shù)
? ? short replicas()default 1;//每個分區(qū)的默認備份數(shù)
? ? StringrefreshInterval()default "1s";//刷新間隔
? ? StringindexStoreType()default "fs";//索引文件存儲類型
? ? boolean createIndex()default true;//是否創(chuàng)建索引
}
(2)@Field
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
@Inherited
public @interface Field {
FieldTypetype()default FieldType.Auto;//自動檢測屬性的類型
? ? boolean index()default true;//是否創(chuàng)建屬性的索引
? ? DateFormatformat()default DateFormat.none;//日期格式
? ? Stringpattern()default "";//驗證的正則表達式
? ? boolean store()default false;//是否存儲
? ? boolean fielddata()default false;//是否延遲加載
? ? StringsearchAnalyzer()default "";//執(zhí)行字段搜索時使用的分詞器
? ? Stringanalyzer()default "";//存儲字段時指定分詞器
? ? Stringnormalizer()default "";//'lowercast'做小寫變換
? ? String[]ignoreFields()default {};//如果某個字段需要被忽略時加入
? ? boolean includeInParent()default false;//是否解析
? ? String[]copyTo()default {};
}
三丹壕、索引的基本使用
@Resource
private ElasticsearchTemplateelasticsearchTemplate;
@Resource
private NewsRepositoryrepository;
//創(chuàng)建文檔索引
@Test
public void creationIndex() {elasticsearchTemplate.createIndex(NewsEntity.class); }
//設置映射關系(把文檔類中的屬性結構和Elasticsearch內部結構對應)
@Test
public void creationMapping() {elasticsearchTemplate.putMapping(NewsEntity.class); }
//刪除索引
@Test
public void deleteIndex() {elasticsearchTemplate.deleteIndex(NewsEntity.class); }
四锈死、文檔操作
@Resource
private NewsRepositoryrepository;
NewsEntitynewsEntity =new NewsEntity();
//添加
@Test
private void saveDocument(NewsEntity newsEntity) {repository.save(newsEntity); }
//刪除
@Test
private void deleteDocument(NewsEntity newsEntity) {repository.delete(newsEntity);}
//批量添加
@Test
public void saveDocuments(List<NewsEntity> newsEntities) {repository.saveAll(newsEntities); }
//更新
//elasticsearch和Lucene一樣沒有提供更新方法,想要更新就需要重新添加,但必須保持文檔主鍵一致
@Test
public void updateDocument(NewsEntity newsEntity) {repository.save(newsEntity);}
//分頁查詢
@Test
public void pageSearch() {
//第一個參數(shù)是分頁數(shù),從零開始計數(shù)表示第一頁
? ? //第二個參數(shù)是分頁的條目數(shù)
? ? Page<NewsEntity> newsEntityPage =repository.findAll(PageRequest.of(0, 2));
}
//按字段排序查詢
@Test
public void sort() {
//查詢所有的里面指定排序的字段祖搓,并可以繼續(xù)調用排序方式(升ascending降descending),默認降序
? ? Iterable<NewsEntity> newsEntities =repository.findAll(Sort.by("sort").descending());
}
Dao類:
@Component
public interface NewsRepositoryextends ElasticsearchRepository {
/**
? ? * 根據(jù)標題查詢
? ? * @param title
? ? * @return
? ? */
? public List<NewsEntity>?findByTitle(String title);
? ? /**
? ? * 根據(jù)兩個數(shù)字區(qū)間查詢
? ? * @param addtime1
? ? * @param addtime2
? ? * @return
? ? */
? public List<NewsEntity>?findByAddtime(Integer addtime1,Integer addtime2);
}
//詞條查詢
@Test
public void termSearch() { List entities =repository.findByTitle("獎學金"); }
//范圍查詢
@Test
public void addTimeSearch() { List entities =repository.findByAddtime(0,120315356); }
//自定義查詢(自己構造查詢條件佑力,對比基礎查詢,搜索內容有了條件)
? ? @Test
? ? public void termSearch1() {
//創(chuàng)建查詢條件生成器
? ? ? ? NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? ? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("title","獎學金"));
? ? ? ? //查詢到的結果植袍,自動分頁伪很,默認第一頁,每頁條目數(shù)是10條(itemRepository相當于文檔讀取器奋单,參數(shù)中的文檔查詢對象需要構建下)
? ? ? ? //在查詢條件生成器中生成查詢對象所以去build構建
????????//Pageable pageable = new PageRequest(1,10);
????????//nativeSearchQueryBuilder.withPageable(pageable);
? ? ? ? Page entityPage =repository.search(nativeSearchQueryBuilder.build());
? ? }
//match匹配查詢
@Test
public void matchSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("title","獎學金"));
? ? Page<NewsEntity>?newsEntityPage =repository.search(nativeSearchQueryBuilder.build());
}
//布爾查詢(綜合查詢)
@Test
public void boolenSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("title","獎學金"))
.must(QueryBuilders.matchQuery("source","Qq")));
? ? Page<NewsEntity> newsEntityPage =repository.search(nativeSearchQueryBuilder.build());
}
//容錯查詢(最多錯兩個)
@Test
public void fuzzSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.fuzzyQuery("title","獎學金"));
? ? Page newsEntityPage =repository.search(nativeSearchQueryBuilder.build());
? ? System.out.println();
}
//模糊查詢
//? 表示詢問一個未知的占位符锉试,* 表示詢問0到n個任意占位符
@Test
public void wildCardSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.wildcardQuery("title","*獎*"));
? ? Page newsEntityPage =repository.search(nativeSearchQueryBuilder.build());
}
//分頁查詢
@Test
public void pageSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.wildcardQuery("title","*獎*"));
? ? //構建分頁
? ? nativeSearchQueryBuilder.withPageable(PageRequest.of(1,10));
? ? Page newsEntityPage =repository.search(nativeSearchQueryBuilder.build());
}
//排序查詢
@Test
public void sortSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.withQuery(QueryBuilders.wildcardQuery("title","*獎*"));
? ? //構建排序
? ? nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("addtime").order(SortOrder.DESC));
? ? Page newsEntityPage =repository.search(nativeSearchQueryBuilder.build());
}
以上可以進行組合查詢,只要不違反規(guī)則便可以累加
聚合查詢
//包含子聚合的聚合查詢
@Test
public void aggregationSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
? ? nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("sources").field("source"));
? ? //查詢
? ? AggregatedPage aggregatedPage = (AggregatedPage)repository.search(nativeSearchQueryBuilder.build());
? ? //根據(jù)聚合名稱獲取對應的聚合
? ? StringTerms sources = (StringTerms) aggregatedPage.getAggregation("sources");
? ? //獲取查詢到的桶
? ? List buckets = sources.getBuckets();
? ? for (StringTerms.Bucket b : buckets) {
System.out.println("來源:"+b.getKeyAsString()+"文檔數(shù):"+b.getDocCount());
? ? }
}