在Spring Boot中配置ElasticSearch

x33g5p2x  于2022-10-04 转载在 Spring  
字(5.6k)|赞(0)|评价(0)|浏览(654)

Elasticsearch是一个开源的、RESTful的、分布式的搜索/分析引擎,建立在Apache Lucene之上。在本教程中,我们将学习如何从Spring Boot连接到它并在其中存储数据。

显然,第一个要求是安装所有产品(反正DockerHub上也有Docker镜像)。你可以在以下网址下载所有ELK产品的最新稳定版本:https://www.elastic.co/downloads

下载完成后,将压缩文件安装到你喜欢的文件夹中,你就完成了安装。

创建Spring Boot项目

如果你正在开发一个简单的Standalone应用程序,你所需要的就是ElasticSearch的依赖。在CLI中执行。

  1. $ spring init -ddata-elasticsearch -artifactId data-elasticsearch-demo

以下依赖关系将被添加。

  1. <?xml version="1.0" encoding="UTF-8"?><project>
  2. <dependencies>
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-test</artifactId>
  14. <scope>test</scope>
  15. </dependency>
  16. </dependencies>
  17. </project>

在我们开始编码之前,重要的是我们要提供你的ElasticSearch服务器的地址和端口,默认的是。

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

编码Spring Boot应用程序

首先,我们需要一个模型对象。我们可以称它为Person。

  1. package com.example.elasticsearch.model;
  2. import org.springframework.data.annotation.Id;
  3. import org.springframework.data.elasticsearch.annotations.Document;
  4. @Document(indexName = "springbootdemo", type = "person")
  5. public class Person {
  6. @Id private String id;
  7. private String firstname;
  8. private String lastname;
  9. private int age;
  10. public Person() {}
  11. public Person(String id, String firstname, String lastname, int age) {
  12. this.id = id;
  13. this.firstname = firstname;
  14. this.lastname = lastname;
  15. this.age = age;
  16. }
  17. public void setFirstname(String firstname) {
  18. this.firstname = firstname;
  19. }
  20. public String getFirstname() {
  21. return this.firstname;
  22. }
  23. public void setLastname(String lastname) {
  24. this.lastname = lastname;
  25. }
  26. public String getLastname() {
  27. return this.lastname;
  28. }
  29. public void setAge(int age) {
  30. this.age = age;
  31. }
  32. public int getAge() {
  33. return this.age;
  34. }
  35. public String toString() {
  36. String info =
  37. String.format(
  38. "Person Info: id = %s, firstname = %s, lastname = %s, age = %d",
  39. id, firstname, lastname, age);
  40. return info;
  41. }
  42. }

然后,我们需要一个扩展了org.springframework.data.elasticsearch.repository.ElasticsearchRepository的Repository接口,以提供对我们模型的CRUD访问。

  1. package com.example.elasticsearch.repository;
  2. import java.util.List;
  3. import com.example.elasticsearch.model.Person;
  4. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  5. public interface PersonRepository extends ElasticsearchRepository<Person, String> {
  6. List<Person> findByFirstname(String firstname);
  7. List<Person> findByAge(int age);
  8. }

最后,我们将添加一个Application类,该类引导SpringBoot并在ElasticSearch中插入一些文档。

  1. package com.example.elasticsearch;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import com.example.elasticsearch.model.Person;
  5. import com.example.elasticsearch.repository.PersonRepository;
  6. import org.springframework.boot.CommandLineRunner;
  7. import org.springframework.boot.SpringApplication;
  8. import org.springframework.boot.autoconfigure.SpringBootApplication;
  9. @SpringBootApplication public class SpringBootElasticSearchApplication implements CommandLineRunner {
  10. @Resource PersonRepository personRepository;
  11. public static void main(String[] args) {
  12. SpringApplication.run(SpringBootElasticSearchApplication.class, args);
  13. }
  14. @Override public void run(String...arg0) throws Exception {
  15. Person p1 = new Person("1", "Jack", "Smith", 20);
  16. Person p2 = new Person("2", "Lucas", "Derrik", 30);
  17. Person p3 = new Person("3", "Andy", "Miller", 40);
  18. System.out.println("Save Persons");
  19. personRepository.save(p1);
  20. personRepository.save(p2);
  21. personRepository.save(p3);
  22. // findAll
  23. System.out.println("Find All");
  24. Iterable < Person > persons = personRepository.findAll();
  25. persons.forEach(System.out::println);
  26. // find customers by firstname = Peter
  27. System.out.println("Find by firstname is Jack");
  28. List < Person > jack = personRepository.findByFirstname("Jack");
  29. jack.forEach(System.out::println);
  30. // find persons having age = 20
  31. System.out.println("Find by age = 20");
  32. List < Person > pers_age_20 = personRepository.findByAge(20);
  33. pers_age_20.forEach(System.out::println);
  34. // delete a person having age = 20
  35. System.out.println("Delete a Person having age = 20");
  36. personRepository.delete(pers_age_20.get(0));
  37. }
  38. }

这就是全部。按照你的喜好运行你的应用程序(例如用java -jar target/application.jar),并在Elastic Search日志中检查。

  1. [2018-12-14T10:20:06,976][INFO ][o.e.c.m.MetaDataCreateIndexService] [1VrMuHj] [springbootdemo] creating index, cause [api], templates [], shards [5]/[1], mappings []

你可以使用Elastic Search REST API来检查索引的列表。

  1. $ curl http://localhost:9200/_cat/indices?v health status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open springbootdemo FMclnijGTiieo3iXzSLdtA 5 1 2 0 9.3kb 9.3kb

很好。我们也可以按如下方式查询我们的索引中的条目。

  1. curl http://localhost:9200/springbootdemo/_search?pretty=true&q=*:* [1] 26576 ~:$ { "took" : 1, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : 2, "max_score" : 1.0, "hits" : [ { "_index" : "springbootdemo", "_type" : "person", "_id" : "2", "_score" : 1.0, "_source" : { "firstname" : "Lucas", "lastname" : "Derrik", "age" : 30 } }, { "_index" : "springbootdemo", "_type" : "person", "_id" : "3", "_score" : 1.0, "_source" : { "firstname" : "Andy", "lastname" : "Miller", "age" : 40 } } ] } }

享受Spring Boot和Elastic Search吧

相关文章