在Spring Boot中配置ElasticSearch

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

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

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

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

创建Spring Boot项目

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

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

以下依赖关系将被添加。

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependencies>
                
      <dependency>
                      
         <groupId>org.springframework.boot</groupId>
                      
         <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
              
      </dependency>
           
      <dependency>
                  
         <groupId>org.springframework.boot</groupId>
                  
         <artifactId>spring-boot-starter-web</artifactId>
              
      </dependency>
            
      <dependency>
                  
         <groupId>org.springframework.boot</groupId>
                  
         <artifactId>spring-boot-starter-test</artifactId>
                  
         <scope>test</scope>
              
      </dependency>
       
   </dependencies>
    
</project>

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

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

编码Spring Boot应用程序

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

package com.example.elasticsearch.model;

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

@Document(indexName = "springbootdemo", type = "person")
public class Person {
  @Id private String id;
  private String firstname;
  private String lastname;
  private int age;

  public Person() {}

  public Person(String id, String firstname, String lastname, int age) {
    this.id = id;
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
  }

  public void setFirstname(String firstname) {
    this.firstname = firstname;
  }

  public String getFirstname() {
    return this.firstname;
  }

  public void setLastname(String lastname) {
    this.lastname = lastname;
  }

  public String getLastname() {
    return this.lastname;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public int getAge() {
    return this.age;
  }

  public String toString() {
    String info =
        String.format(
            "Person Info: id = %s, firstname = %s, lastname = %s, age = %d",
            id, firstname, lastname, age);
    return info;
  }
}

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

package com.example.elasticsearch.repository;

import java.util.List;
import com.example.elasticsearch.model.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface PersonRepository extends ElasticsearchRepository<Person, String> {
  List<Person> findByFirstname(String firstname);

  List<Person> findByAge(int age);
}

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

package com.example.elasticsearch;
import java.util.List;
import javax.annotation.Resource;
import com.example.elasticsearch.model.Person;
import com.example.elasticsearch.repository.PersonRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class SpringBootElasticSearchApplication implements CommandLineRunner {
  @Resource PersonRepository personRepository;
  public static void main(String[] args) {
    SpringApplication.run(SpringBootElasticSearchApplication.class, args);
  }
  @Override public void run(String...arg0) throws Exception {
    Person p1 = new Person("1", "Jack", "Smith", 20);
    Person p2 = new Person("2", "Lucas", "Derrik", 30);
    Person p3 = new Person("3", "Andy", "Miller", 40);
    System.out.println("Save Persons");
    personRepository.save(p1);
    personRepository.save(p2);
    personRepository.save(p3);
    // findAll
    System.out.println("Find All");
    Iterable < Person > persons = personRepository.findAll();
    persons.forEach(System.out::println);
    // find customers by firstname = Peter         
    System.out.println("Find by firstname is Jack");
    List < Person > jack = personRepository.findByFirstname("Jack");
    jack.forEach(System.out::println);
    // find persons having age = 20         
    System.out.println("Find by age = 20");
    List < Person > pers_age_20 = personRepository.findByAge(20);
    pers_age_20.forEach(System.out::println);
    // delete a person having age = 20
    System.out.println("Delete a Person having age = 20");
    personRepository.delete(pers_age_20.get(0));
  }
}

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

[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来检查索引的列表。

$ 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

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

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吧

相关文章

微信公众号

最新文章

更多