springboot與elasticsearch整合


資源下載:
ElasticSearch官方下載地址:https://www.elastic.co/downloads/elasticsearch
curl下載地址:http://curl.haxx.se/download.html
Kibana下載地址:https://www.elastic.co/guide/en/kibana/4.6/index.html
sense下載地址:https://download.elastic.co/elastic/sense/sense-latest.tar.gz
ik分詞器下載地址:https://github.com/medcl/elasticsearch-analysis-ik
logstash下載地址:https://www.elastic.co/cn/downloads/logstash
elasticsearch官網地址:https://www.elastic.co
注意:ElasticSearch和Kibana版本必須一致
我用到的elasticsearch版本和Kibana是 6.4.3
1,查看本地項目spring和springboot版本號

public static void main(String[] args) {
    System.out.println(SpringVersion.getVersion());
    System.out.println(SpringBootVersion.getVersion());
}

2,導入相關依賴

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

3,application.yml配置文件

#es配置
spring:
data:
  elasticsearch:
    cluster-name: elasticsearch //默認集群名稱
    cluster-nodes: 127.0.0.1:9300 //默認啟動集群節點

4,啟動類配置@EnableElasticsearchRepositories(basePackages = “com.aigezi.cdd.entity.dao.es”), basePackages是es資源庫所在包

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.aigezi.cdd.entity.dao.es")
public class SpringbootElasticsearchApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootElasticsearchApplication.class, args);
    }
}

5,索引文檔實體 注意此時@Id注解的導入包來自import org.springframework.data.annotation.Id,索引名稱必須為小寫

@Document(indexName = "product", type = "book")
@Data
public class Book {
   @Id
   String id; 
   String name;
   String message;
   String type;

   public Book(){}

   public Book(String id,String name,String message,String type){
      this.id = id;
      this.name = name;
      this.message = message;
      this.type = type;
   }

}

6,elasticsearch資源庫 繼承了ElasticsearchRepository,封裝了很多API

@Component
public interface BookRepository extends ElasticsearchRepository<Book,String> { // Book是索引文檔實體,String是文檔id類型
}

7,Controller 層 增刪改查操作

@Resource
BookRepository bookRepository;

@ApiOperation("創建索引")
@PostMapping("/auth/add")
public String add(){
    Book book = new Book();
    book.setId("1");
    book.setMessage("TTTTGGGGDDD");
    book.setType("es");
    book.setName("spring");
    bookRepository.save(book);
    return "success";
}

8,在Kibana訪問新建索引

GET /product/book/_search

查詢結果:
{
        "_index": "product",
        "_type": "book",
        "_id": "1",
        "_score": 1,
        "_source": {
          "id": "1",
          "name": "spring",
          "message": "TTTTGGGGDDD",
          "type": "es"
        }
      }

 

END !!!


免責聲明!

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



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