1. 程式人生 > >springboot 與檢索—使用、原理、整合ElasticSearch

springboot 與檢索—使用、原理、整合ElasticSearch

        ElasticSearch--全文搜尋引擎的首選:面向文件,它儲存整個物件或文件。使用json作為文件的序列化格式(一個json文件就代表一個物件)。

        springboot(版本:2.0.2.RELEASE)整合elasticsearch:

       1、springboot預設支援有兩種技術來和elasticsearch互動(Jest/SpringData ElasticSearch)

              Jest預設不生效@ConditionalOnClass({JestClient.class}) 需要匯入Jest工具包:io.searchbox.client.JestClient;

       2、使用SpringData ElasticSearch與ElasticSearch互動原理

               ElasticsearchAutoConfiguration :自動配置了客戶端TransportClient,需要配置節點資訊 clusterName、clusterNodes

               寫個介面繼承該介面,就會有ElasticsearchCrudRepository (可以對elasticsearch的增刪改查操作)

               ElasticsearchRepositoriesAutoConfiguration:啟用了ElasticsearchRepository(類似於jpa的程式設計方式)的介面,可以編寫一個ElasticsearchRepository的子介面來操作ES。

       3、以Jest方式與ES互動測試

          1)註釋spring-boot-starter-data-elasticsearch ,引入Jest包

<dependency>
   	<groupId>io.searchbox</groupId>
   	<artifactId>jest</artifactId>
   	<version>6.3.0</version>
</dependency>

         2)引入Jest包後JestAutoConfiguration 該自動配置將生效,生效後需要配置相應的屬性

#地址
spring.elasticsearch.jest.uris=http://localhost:9200

       3)啟動專案

     4)測試(jest官方文件:https://github.com/searchbox-io/Jest/tree/master/jest)

package com.example.bean;

import io.searchbox.annotations.JestId;

public class Article {
    //給id欄位添加註解,@JestId表示這是一個主鍵
    @JestId
    private Integer id;
    private String author;
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

          索引文件

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests implements Serializable {
    @Autowired
	JestClient jestClient;

	@Test
	public void jestTest() {
		//1、給ES中索引(儲存)一個文件
		Article article = new Article();
		article.setId(1);
		article.setTitle("好訊息");
		article.setAuthor("zhansan");
		article.setContent("Hello World");

		//構建一個索引功能 :Index.Builder(儲存的內容).index(指定索引位置).type(指定型別).id(指定id).build()
		Index index = new Index.Builder(article).index("mytest").type("news").build();

		try {
			//執行
			jestClient.execute(index);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

             根據索引/型別/id檢索

            測試查詢

@Test
public void search(){
	//查詢表示式
	String json = "{\n" +
			"    \"query\" : {\n" +
			"    	\"match\" : {\n" +
			"    		\"content\" : \"hello\"\n" +
			"    	}\n" +
			"    }\n" +
			"}";
	//構建搜尋功能
	Search search = new Search.Builder(json).addIndex("mytest").addType("news").build();
	try {
		//執行
		SearchResult result = jestClient.execute(search);
		System.out.println(result.getJsonString());
	} catch (Exception e) {
		e.printStackTrace();
	}
}

               執行結果如下 :

        4、以Spring Data方式與ES互動測試

            1)引入依賴  

<!--springboot 預設使用springdate elasticsearch模組進行操作-->
<dependency>
   	<groupId>org.springframework.boot</groupId>
   	<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

          2)配置

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300

         3)版本適配說明(https://github.com/spring-projects/spring-data-elasticsearch)

            如果版本不適配:升級springboot版本或安裝對應版本的ES

package com.example.config;

import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class ElasticSearchConfig {
    @PostConstruct
    void init() {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }
}

       4)編寫一個ElasticRepository的子介面(參考文件:https://github.com/spring-projects/spring-data-elasticsearch)

package com.example.repository;

import com.example.bean.BookTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

public interface BookRepository extends ElasticsearchRepository <BookTest,Integer>{
    public List<BookTest> findByBookNameLike(String bookName);//自定義方法
}

        測試:

package com.example.bean;

import org.springframework.data.elasticsearch.annotations.Document;
//標註儲存地址
@Document(indexName = "mytest",type="book")
public class BookTest {
    private Integer id;
    private String bookName;
    private String author;

    @Override
    public String toString() {
        return "BookTest{" +
                "id=" + id +
                ", bookName='" + bookName + '\'' +
                ", author='" + author + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

          執行測試方法:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests implements Serializable {
    @Autowired
	BookRepository bookRepository;

	@Test
	public void test03(){
		/*for(BookTest bookTest : bookRepository.findByBookNameLike("遊")){
			System.out.println(bookTest);
		}*///自定義方法測試
		BookTest bookTest = new BookTest();
		bookTest.setId(1);
		bookTest.setBookName("西遊記");
		bookTest.setAuthor("吳承恩");
		bookRepository.index(bookTest);
	}
}

            檢視elasticsearch中的值

           BookRepository中的基本方法:

   5)自定義方法命名規則參考參考文件https://docs.spring.io/spring-data/elasticsearch/docs/3.0.9.RELEASE/reference/html/