Spring Data Elasticsearch
以POJO為中心模型用于與Elastichsearch文檔交互,并輕松編寫存儲庫樣式的數(shù)據(jù)訪問層框架
我們學習的是底層封裝了Rest High Level的ElasticsearchRestTemplate模板類型。需要使用Java API Client(Transport),則應(yīng)用ElasticsearchTemplate模板類型即可。兩種類型中的方法API幾乎完全一樣,學會了一個,另外一個主要就是配置和類型的區(qū)別。當然了,每個不同版本的框架,在方法API上還是有些差異的。
Spring Data Elasticsearch訪問Elasticsearch
準備環(huán)境
1.導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.yml配置
# ElasticsearchRestTemplate客戶端的配置
spring:
elasticsearch:
rest:
uris: http://127.0.0.1:9200 # ES服務(wù)器所在位置。集群多節(jié)點地址用逗號分隔。默認http://localhost:9200
3.創(chuàng)建實體類
* Document - 描述類型和索引的映射。
* indexName - 索引名稱
* shards - 主分片數(shù)量。默認值 1。
* replicas - 副本分片數(shù)量。默認值 1。
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "xy_student",shards = 1,replicas = 0)
public class Student {
* Id - 當前注解所在字段和主鍵值一致,沒有次注解,則自動生成主鍵
* Field - 當前屬性和索引中的字段映射規(guī)則。
* name - 字段名稱。默認和當前類型屬性名一致。
* type - 字段類型。默認使用FieldType.AUTO。自動識別。
* analyzer - 分詞器。所有的Text類型字段默認使用standard分詞器。
* index - 是否創(chuàng)建索引。默認值 true。
* format - 如果字段類型是date日期類型。此屬性必須配置,用于設(shè)置日期格式化規(guī)則,使用DateFormat類型中的常量定義。
@Id
@Field(name="sid",type = FieldType.Integer)
private Integer sid;
@Field(name="sname",type = FieldType.Text,analyzer = "ik_max_word")
private String sname;
@Field(name="score",type = FieldType.Double)
private Double score;
@Field(name="birth",type = FieldType.Date,format = DateFormat.year_month_day)
private Date birth;
}
索引操作
@Autowired
private ElasticsearchRestTemplate restTemplate;
IndexOperations indexOps = restTemplate.indexOps(Student.class);
1.創(chuàng)建索引
indexOps.create();
2.設(shè)置映射: 在商業(yè)開發(fā)中,幾乎不會使用框架創(chuàng)建索引或設(shè)置映射。因為這是架構(gòu)或者管理員的工作。且不適合使用代碼實現(xiàn)
indexOps.putMapping(indexOps.createMapping());
3.刪除索引
restTemplate.indexOps(Student.class).delete();
文檔操作
簡單CURD
1.新增文檔
如果索引不存在,新增文檔時自動創(chuàng)建索引。但是不使用類上的映射配置,使用默認映射.所以一定要先通過代碼進行mapping設(shè)置,或直接在elasticsearch中通過命令創(chuàng)建所有field的mapping(推薦)
Student zs = elasticsearchRestTemplate.save(new Student(1, "zs", 0.55, new Date()));
System.out.println(zs);
2.批量新增文檔
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(1, "zs", 0.55, new Date()));
students.add(new Student(2, "sdf", 0.22, new Date()));
students.add(new Student(3, "df", 0.33, new Date()));
Iterable<Student> save = elasticsearchRestTemplate.save(students);
System.out.println(save.toString());
3.主鍵查詢文檔
Student student = restTemplate.get("3", Student.class);
4.刪除文檔
// 刪除類型對應(yīng)的索引中的指定主鍵數(shù)據(jù),返回刪除數(shù)據(jù)的主鍵。注意:Elasticsearch中的文檔主鍵都是字符串類型的。
String response = restTemplate.delete("1", Student.class);
5.更新文檔
* save方法,可以覆蓋同主鍵數(shù)據(jù)。全量替換
* update更新,部分更新
@Test
public void testUpdate(){
UpdateQuery query =UpdateQuery.builder("2")
.withDocument(Document.parse("{\"hobbies\":[\"郭麒麟\", \"郭汾陽\"]}"))
.build();
UpdateResponse response = restTemplate.update(query, IndexCoordinates.of("stu_index"));
System.out.println(response.getResult());
}
query string 查詢文章來源:http://www.zghlxwxcb.cn/news/detail-511142.html
@Test
void contextsxLsoads() {
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("sname:zs");
Query query = new NativeSearchQueryBuilder()
.withQuery(queryBuilder) // 提供具體的條件。
.build();
SearchHits<Student> hits = elasticsearchRestTemplate.search(query, Student.class);
System.out.println("搜索結(jié)果數(shù)據(jù)個數(shù)是: " + hits.getTotalHits());
for (SearchHit<Student> hit : hits) {
// 源數(shù)據(jù),就是保存在Elasticsearch中的數(shù)據(jù)
Student content = hit.getContent();
System.out.println("源數(shù)據(jù):" + content);
}
}
DSL 查詢文章來源地址http://www.zghlxwxcb.cn/news/detail-511142.html
1.搜索全部
@Test
public void testMatchAll(){
SearchHits<Student> hits = restTemplate.search(
new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery())
.build(), Student.class);
for(SearchHit<Student> hit : hits){
System.out.println(hit.getContent());
}
}
2.match搜索
SearchHits<Student> hits = restTemplate.search(
new NativeSearchQueryBuilder()
.withQuery(
QueryBuilders.matchQuery(
"name",
"于謙")
).build(),Student.clas);
3.短語搜索,完全匹配Match Phrase
SearchHits<Student> hits = restTemplate.search(
new NativeSearchQueryBuilder()
.withQuery(
QueryBuilders.matchPhraseQuery(
"hobbies",
"燙頭"
)
)
.build(),
Student.class
);
4.范圍搜索Range 搜索
SearchHits<Student> hits =
restTemplate.search(
new NativeSearchQueryBuilder()
.withQuery(
QueryBuilders.rangeQuery("age")
.lte(35).gte(30)
)
.build(),
Student.class
);
5.Bool 搜索,多條件同時滿足
@Test
void contextswLsoads() {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
List<QueryBuilder> must = boolQueryBuilder.must();
must.add(QueryBuilders.matchQuery("sname","zs"));
must.add(QueryBuilders.rangeQuery("score").gt(0).lt(0.5));
Query queryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
SearchHits<Student> search = elasticsearchRestTemplate.search(queryBuilder, Student.class);
}
6.分頁和排序
* PageRequest類型中,提供靜態(tài)方法of(int page, int size[, Sort sort]);
* page - 查詢第幾頁,頁碼數(shù)字從0開始計數(shù)。
* size - 查詢多少行。
* Sort - 具體的排序規(guī)則??蛇x參數(shù)。
SearchHits<Student> hits =
restTemplate.search(
new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery())
.withPageable(
PageRequest.of(0, 2,
Sort.by(
Sort.Order.desc("age"),
Sort.Order.asc("id")
)
)
)
.build(),
Student.class
);
7.高亮處理
@Test
public void testQueryHighLight(){
// 創(chuàng)建高亮字段,必須和具體的字段名綁定。
HighlightBuilder.Field field1 = new HighlightBuilder.Field("name");
// 高亮前綴
field1.preTags("<span style='color: red'>");
// 高亮后綴
field1.postTags("</span>");
// 分段的每段字符數(shù)
field1.fragmentSize(Integer.MAX_VALUE);
// 分段后,返回幾段
field1.numOfFragments(1);
Query query =
new NativeSearchQueryBuilder()
.withQuery(
QueryBuilders.matchQuery(
"name",
"于謙")
)
.withHighlightFields(field1)
.build();
SearchHits<Student> hits =
restTemplate.search(query, Student.class);
for (SearchHit<Student> hit : hits){
// 獲取源數(shù)據(jù)
Student content = hit.getContent();
// 找高亮數(shù)據(jù)
List<String> hl = hit.getHighlightField("name");
// 判斷是否有高亮數(shù)據(jù)
if(hl != null && hl.size() > 0){
// 有高亮數(shù)據(jù)
content.setName(hl.get(0));
}
System.out.println(content);
}
}
到了這里,關(guān)于Spring Data Elasticsearch配置及使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!