如何使用springData來操作es

這篇文章主要介紹“如何使用springData來操作es”,在日常操作中,相信很多人在如何使用springData來操作es問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用springData來操作es”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

公司主營業(yè)務(wù):成都做網(wǎng)站、網(wǎng)站設(shè)計、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)推出陸川免費做網(wǎng)站回饋大家。

1 Es 的配置文件 elasticsearch.yml

http.cors.enabled: true
http.cors.allow-origin: "*"

network.host: 127.0.0.1

2 配置中文分詞器 (見之前的博客)

3 導(dǎo)入jar

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.7.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			 <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
         </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

4 編寫配置文件 (7.3 暫時springdata暫時不支持)

# elasticsearch-6.5.4 需要再配置文件配置上ip地址
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
#設(shè)置連接超時時間
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s

5 實體類上增加注解

/**
 * @author shihaifeng
 * @date 2019-08-29 14:06
 * @desc (描述)
 **/
@Document(indexName = "book",type = "user")
public class Book implements Serializable{
    @Id     //主鍵
    private Integer id;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String name;

    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String context;

    @Field(type = FieldType.Text, analyzer = "ik_smart")
    private String auto;
}

6 編寫接口

package com.example.demo.inter;

import com.example.demo.entity.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * @author shihaifeng
 * @date 2019-08-29 14:47
 * @desc (書接口 - 用來直接操作)
 *
 *  Book 實體對象
 *  Integer 是主鍵
 **/
public interface IBookServer extends ElasticsearchRepository<Book,Integer> {
}

7 測試

package com.example.demo;

import com.example.demo.entity.Book;
import com.example.demo.inter.IBookServer;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

;

/**
 * @author shihaifeng
 * @date 2019-08-29 14:52
 * @desc (描述)
 **/
@RunWith(SpringRunner.class)
@SpringBootTest
public class BookTest {

    @Autowired
    private IBookServer bookServer;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 添加數(shù)據(jù)
     */
    @Test
    public void addBook() {
        //添加一條數(shù)據(jù)
        bookServer.save(new Book(1, "書名", "書內(nèi)容", "作者"));

        List<Book> list = new ArrayList<>();
        list.add(new Book(2, "《阿彌陀佛么么噠》", "大冰,本名焉冰,1980年10月23日出生于山東省煙臺市萊陽市,中國內(nèi)地主持人、民謠歌手、作家、油畫畫師,畢業(yè)于山東藝術(shù)學(xué)院。", "大冰"));
        list.add(new Book(3, "《我不》", "善意能消戾,善意能得緣,善意能帶業(yè)往生,善意能回頭是岸。 善意能夠幫人捕捉并建立起獨特的幸福感。 “我不”是一種善意坦然,也是一種善意的隨緣,更是一句善意的自省", "大冰"));
        list.add(new Book(4, "《乖,摸摸頭》", "是由主持人大冰所著,湖南文藝出版社的一本記錄了大冰十余年的江湖游歷,以及他和他朋友們的愛與溫暖的傳奇故事的書籍。", "大冰"));
        list.add(new Book(5, "《他們最幸?!?quot;, "書中講述的故事是有關(guān)于主角大冰一段十年的精彩生長之路,也是路途中十個不同他們幸福的故事,更是一段對當(dāng)下價值觀有形無聲的生活抗議。 多棲身份的大冰,從主持人到民謠歌手,從江湖游俠到資深文青,他抱著一只手鼓行唱在天涯中,卻從未將故事寫在紙面上。", "大冰"));

        list.add(new Book(6, "《邊城》", "沈從文的創(chuàng)作風(fēng)格趨向浪漫主義,他要求小說的詩意效果,融寫實、紀(jì)夢、象征于一體,語言格調(diào)古樸,\n" +
                "沈從文及其作品沈從文及其作品(5張)句式簡峭、主干突出,單純而又厚實,樸訥而又傳神", "沈從文"));
        list.add(new Book(7, "《湘行散記》", "沈從文是具有特殊意義的鄉(xiāng)村世界的主要表現(xiàn)者和反思者,他認(rèn)為“美在生命”,雖身處于虛偽、自私和冷漠的都市,卻醉心于人性之美", "沈從文"));
        list.add(new Book(8, "《長河》", "“我不知道為什么忽然愛上你了?!鄙頌槿握n教師的沈從文悄悄地給學(xué)生張兆和寫信,他在信里這么說。", "沈從文"));
        bookServer.saveAll(list);//批量添加數(shù)據(jù)
    }

    /**
     * 查詢信息
     */
    @Test
    public void query() {
        Optional<Book> book = bookServer.findById(3);
        System.out.println("------------findById-----------------");
        System.out.println(book.get().toString());

        Iterable<Book> books = bookServer.findAll();
        System.out.println("------------findAll-----------------");
        for (Book book1 : books) {
            System.out.println(book1);
        }

        System.out.println("------------search QueryBuilder-----------------");
        Page<Book> search = bookServer.search(new TermQueryBuilder("context", "沈從文"), PageRequest.of(0, 10));
        for (Book book1 : search.getContent()) {
            System.out.println(book1);
        }

        System.out.println("------------search SearchQuery (高亮顯示)-----------------");
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("context", "沈從文"))       //設(shè)置查詢內(nèi)容
                .withHighlightFields(new HighlightBuilder.Field("context").preTags("<前綴>").postTags("</后綴>")).build()  //設(shè)置高亮顯示
                .setPageable(PageRequest.of(0, 10));//設(shè)置分頁信息
        AggregatedPage<Book> page = elasticsearchTemplate.queryForPage(searchQuery, Book.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                //返回結(jié)果集重新映射
                List<Book> list = new ArrayList<>();

                SearchHits hits = searchResponse.getHits();
                Iterator<SearchHit> iterator = hits.iterator();
                while (iterator.hasNext()){
                    Book book = new Book();
                    SearchHit searchHit = iterator.next();

                    Map<String, Object> source = searchHit.getSourceAsMap();
                    book.setId(Integer.valueOf(source.get("id").toString()));//設(shè)置id
                    book.setName(source.get("name").toString());//設(shè)置書名
                    book.setAuto(source.get("auto").toString());//設(shè)置作者

                    Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();//獲取高亮顯示的列
                    book.setContext(highlightFields.get("context").toString());//設(shè)置高亮顯示的列
                    System.out.println("高亮顯示的值是 = " + highlightFields.get("context"));

                    list.add(book);
                }

                //返回查詢的結(jié)果
                return new AggregatedPageImpl(list);
            }
        });
        List<Book> content = page.getContent();
        System.out.println("查出的總數(shù)是 = " + content.size());
    }


    /**
     * 跟新數(shù)據(jù)
     */
    @Test
    public void update(){
        bookServer.save(new Book(1, "書名3", "書內(nèi)容3", "作者3"));
    }

    /**
     * 刪除數(shù)據(jù)
     */
    @Test
    public void delete(){
        bookServer.delete(new Book(1, "書名3", "書內(nèi)容3", "作者3"));
    }

}

到此,關(guān)于“如何使用springData來操作es”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

分享標(biāo)題:如何使用springData來操作es
URL分享:http://www.muchs.cn/article8/jsodip.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、網(wǎng)站策劃、網(wǎng)站內(nèi)鏈、靜態(tài)網(wǎng)站手機網(wǎng)站建設(shè)、虛擬主機

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)