国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Data Elasticsearch配置及使用

這篇具有很好參考價值的文章主要介紹了Spring Data Elasticsearch配置及使用。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

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 查詢

    @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)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Spring Data Elasticsearch--使用/教程/實例

    Spring Data Elasticsearch--使用/教程/實例

    原文網(wǎng)址:Spring Data Elasticsearch--使用/教程/實例_IT利刃出鞘的博客-CSDN博客 技術(shù)星球 歡迎來到IT技術(shù)星球,網(wǎng)站是:learn.skyofit.com(或者百度直接搜:自學精靈)。內(nèi)容有: Java真實面試題 、 Java設(shè)計模式實戰(zhàn) 、Shiro項目實戰(zhàn)、 Idea和Navicat的“魔法” 教程、 SpringBoot進階 、架構(gòu)

    2023年04月09日
    瀏覽(45)
  • Spring Data Elasticsearch 的簡單使用

    目錄 一、簡介 二、配置 三、映射 四、?常用方法 五、操作(重點) 1、對索引表的操作 2、對文檔的操作(重點) (1)、添加文檔 ?(2)、刪除文檔 (3)、查詢文檔(重點) 查詢?nèi)课臋n?(兩種方式) matchQuery根據(jù)拆分進行全局搜索 matchPhraseQuery短語搜索--完整搜

    2024年02月12日
    瀏覽(17)
  • 【Elasticsearch】spring-boot-starter-data-elasticsearch的使用以及Elasticsearch集群的連接

    【Elasticsearch】spring-boot-starter-data-elasticsearch的使用以及Elasticsearch集群的連接

    更多有關(guān)博主寫的往期Elasticsearch文章 標題 地址 【ElasticSearch 集群】Linux安裝ElasticSearch集群(圖文解說詳細版) https://masiyi.blog.csdn.net/article/details/131109454 基于SpringBoot+ElasticSearch 的Java底層框架的實現(xiàn) https://masiyi.blog.csdn.net/article/details/121534307 ElasticSearch對標Mysql,誰能拔得頭籌

    2024年02月11日
    瀏覽(26)
  • spring data elasticsearch使用7.x客戶端兼容es 8.x和使用ssl構(gòu)建RestHighLevelClient

    es在7.x中默認加入elastic security組件所以java client需要使用ssl連接es server. es 8.x 中廢棄了 RestHighLevelClient ,使用新版的 java api client ,但是spring data elasticsearch還未更新到該版本.所以需要兼容es 8.x 如下是RestHighLevelClient構(gòu)建方法: spring data elasticsearch客戶端依賴(基于spring boot2.7使用最新

    2024年02月13日
    瀏覽(27)
  • spring data系列之Spring data ElasticSearch

    spring data系列之Spring data ElasticSearch

    Spring data ElasticSearch簡介: ?????? Elasticsearch是一個實時的分布式搜索和分析引擎。它底層封裝了Lucene框架,可以提供分布式多用戶的全文搜索服務(wù)。 ?????? Spring Data ElasticSearch是SpringData技術(shù)對ElasticSearch原生API封裝之后的產(chǎn)物,它通過對原生API的封裝,使得程序員可以簡單的

    2023年04月08日
    瀏覽(33)
  • spring-data-elasticsearch使用Sort排序時Please use a keyword field instead. ……異常解決

    spring-data-elasticsearch使用Sort排序時Please use a keyword field instead. ……異常解決

    核心提示在 Please use a keyword field instead. Alternatively, set fielddata=true on [dataTimestamp] in order to load field data by uninverting the inverted index. 待排序字段 dataTimestamp 沒有為排序優(yōu)化,所以無法排序,需要配置 FieldType.Keyword 或 fielddata = true ,可是代碼中都配置了為什么還提示呢,往下看……

    2023年04月24日
    瀏覽(21)
  • spring Data Elasticsearch入門

    spring Data Elasticsearch入門

    1.Elasticsearch Elasticsearch提供了兩種連接方式: transport:通過TCP方式訪問ES。(已廢棄) rest:通過HTTP API 方式訪問ES。 描述: Spring Data Elasticsearch 項目提供了與Elasticsearch 搜索引擎的集成。Spring Data ElasticSearch 的關(guān)鍵功能領(lǐng)域是以POJO為中心的模型,用于與Elastichsearch 文檔交互并

    2024年02月02日
    瀏覽(24)
  • Spring Data ElasticSearch簡介

    Spring Data ElasticSearch簡介

    Spring Data是?個?于簡化數(shù)據(jù)庫訪問,并?持云服務(wù)的開源框架。其主要?標是使得對數(shù)據(jù)的訪問變 得?便快捷,并?持map-reduce框架和云計算數(shù)據(jù)服務(wù)。 Spring Data可以極?的簡化JPA的寫法,可 以在?乎不?寫實現(xiàn)的情況下,實現(xiàn)對數(shù)據(jù)的訪問和操作。除了CRUD外,還包括如分

    2023年04月19日
    瀏覽(18)
  • Spring Data Elasticsearch - 在Spring應(yīng)用中操作Elasticsearch數(shù)據(jù)庫

    Spring Data Elasticsearch為文檔的存儲,查詢,排序和統(tǒng)計提供了一個高度抽象的模板。使用Spring Data ElasticSearch來操作Elasticsearch,可以較大程度的減少我們的代碼量,提高我們的開發(fā)效率。 要使用Elasticsearch我們需要引入如下依賴: 還需要在配置文件中增加如下配置 類比于MyBat

    2024年02月14日
    瀏覽(19)
  • Spring Data Elasticsearch介紹(七)

    Spring Data Elasticsearch介紹(七)

    ????????Spring Data Elasticsearch是Spring Boot套件中的一個組件,在Spring Boot中連接ES可以使用Spring Data Elasticsearch。 ????????Spring Data Elasticsearch是Spring Data項目的一部分,該項目致力于提供一致的基于Spring的數(shù)據(jù)查詢和存儲編程模型。 ????????Spring Data Elasticsearch封裝了創(chuàng)

    2024年02月14日
    瀏覽(26)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包