springboot檢索之整合elasticsearch並使用spring-data操作


各種過時,版本不兼容,只能暫時將代碼放在這先做參考了。

pom.xml

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

Book.java

package com.gong.spingbootes.bean;

import org.springframework.data.elasticsearch.annotations.Document;

//這里必須指明索引名字和類型 @Document(indexName
= "gong",type = "book") public class Book { private Integer id; private String bookName; private String author; public Book(){} public Book(Integer id, String bookName, String author) { this.id = id; this.bookName = bookName; this.author = author; } @Override public String toString() { return "Book{" + "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; } }

BookRepository.java

package com.gong.spingbootes.repository;

import com.gong.spingbootes.bean.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;
//第一個泛型是對象類型,第二個泛型是book的主鍵
public interface BookRepository extends ElasticsearchRepository<Book,Integer>{
   //這里的名字不是隨意取的,而是根據查詢需求來取的,具體可參考相關文檔
public List<Book> findByBookNameLike(String bookName); }

application.properties

spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=192.168.124.22
#這兩玩意過時了

SpringbootEsApplicationTests.java

package com.gong.spingbootes;

import com.gong.spingbootes.bean.Article;
import com.gong.spingbootes.bean.Book;
import com.gong.spingbootes.repository.BookRepository;
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.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class SpingbootEsApplicationTests {

    @Autowired
    BookRepository bookRepository;

    @Test
    public void contextLoads() {
    }

  //添加索引 @Test
public void index() { bookRepository.index(new Book(1,"java","德瑪")); }
  //進行查詢 @Test
public void search() { bookRepository.findByBookNameLike("ja"); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM