一、实体(Entity)
@Document(indexName = "my_index", type = "newsEntity",shards = 1, replicas = 0, refreshInterval = "-1")
//Document :每一条记录就是一篇文档
//indexName :文档的索引名称--唯一标记
//type :文档类型 doc ppt xls story product
//shards : 数据分片个数 默认将数据存6份,5个主份+1个备份
public class NewsEntityextends BaseModel {
//编号id 主键
@Id
String id;
//type : Text表示文本,可被分词也可被索引;Keyword表示关键字,不分词可被索引,但String被分词
//index : true表示可被索引;false表示不可被索引
//store : true表示可被储存;alse表示不可被储存
//analyzer : 执行分词器
@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;//默认分区数
short replicas()default 1;//每个分区的默认备份数
StringrefreshInterval()default "1s";//刷新间隔
StringindexStoreType()default "fs";//索引文件存储类型
boolean createIndex()default true;//是否创建索引
}
(2)@Field
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
@Inherited
public @interface Field {
FieldTypetype()default FieldType.Auto;//自动检测属性的类型
boolean index()default true;//是否创建属性的索引
DateFormatformat()default DateFormat.none;//日期格式
Stringpattern()default "";//验证的正则表达式
boolean store()default false;//是否存储
boolean fielddata()default false;//是否延迟加载
StringsearchAnalyzer()default "";//执行字段搜索时使用的分词器
Stringanalyzer()default "";//存储字段时指定分词器
Stringnormalizer()default "";//'lowercast'做小写变换
String[]ignoreFields()default {};//如果某个字段需要被忽略时加入
boolean includeInParent()default false;//是否解析
String[]copyTo()default {};
}
三、索引的基本使用
@Resource
private ElasticsearchTemplateelasticsearchTemplate;
@Resource
private NewsRepositoryrepository;
//创建文档索引
@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() {
//第一个参数是分页数,从零开始计数表示第一页
//第二个参数是分页的条目数
Page<NewsEntity> newsEntityPage =repository.findAll(PageRequest.of(0, 2));
}
//按字段排序查询
@Test
public void sort() {
//查询所有的里面指定排序的字段,并可以继续调用排序方式(升ascending降descending),默认降序
Iterable<NewsEntity> newsEntities =repository.findAll(Sort.by("sort").descending());
}
Dao类:
@Component
public interface NewsRepositoryextends ElasticsearchRepository {
/**
* 根据标题查询
* @param title
* @return
*/
public List<NewsEntity> findByTitle(String title);
/**
* 根据两个数字区间查询
* @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() {
//创建查询条件生成器
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("title","奖学金"));
//查询到的结果,自动分页,默认第一页,每页条目数是10条(itemRepository相当于文档读取器,参数中的文档查询对象需要构建下)
//在查询条件生成器中生成查询对象所以去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());
}
以上可以进行组合查询,只要不违反规则便可以累加
聚合查询
//包含子聚合的聚合查询
@Test
public void aggregationSearch() {
NativeSearchQueryBuilder nativeSearchQueryBuilder =new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("sources").field("source"));
//查询
AggregatedPage aggregatedPage = (AggregatedPage)repository.search(nativeSearchQueryBuilder.build());
//根据聚合名称获取对应的聚合
StringTerms sources = (StringTerms) aggregatedPage.getAggregation("sources");
//获取查询到的桶
List buckets = sources.getBuckets();
for (StringTerms.Bucket b : buckets) {
System.out.println("来源:"+b.getKeyAsString()+"文档数:"+b.getDocCount());
}
}