Spring Boot + Elasticsearch

The Integration Zone is brought to you in partnership with  3scale. Take control of your APIs and get a free t-shirt when you complete the  3step Challenge

We often use Elasticsearch to improve performance in our application, especially searching and caching, to make our application scale and adapt in real-time.

Elasticsearch is a flexible and powerful open source, distributed, real-time search and analytics engine. In this article, I would like to introduce how to use Elasticsearch in java applications: by using Spring Boot data Elasticsearch. Spring Boot now easy and powerful, and we can build fast Java and web applications with a simple configuration.

By following the steps below, you can start writing your first application.

Source code: https://github.com/herotl2005/spring-data-elasticsearch-sample

Requirement enviroment

1. Install Elasticsearch

2. Install Gradle

3. IDE Eclipse or Intellij  IDEA

Step by Step Coding

1. Gradle build 

dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'org.springframework.boot:spring-boot-starter-data-elasticsearch:1.2.0.RELEASE'
compile 'org.springframework.data:spring-data-cassandra:1.1.1.RELEASE'
compile 'org.springframework:spring-test:4.1.2.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-logging:1.2.0.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-web:1.2.0.RELEASE'
compile 'org.springframework.boot:spring-boot-starter-actuator:1.2.0.RELEASE'
}

2. Elasticsearch configuration

@Configuration@PropertySource(value = "classpath:elasticsearch.properties")
@EnableElasticsearchRepositories(basePackages = "co.paan.repository")
public class ElasticsearchConfiguration {
    @Resource
private Environment environment;
@Bean
public Client client() {
        TransportClient client = new TransportClient();
TransportAddress address = new InetSocketTransportAddress(environment.getProperty("elasticsearch.host"), Integer.parseInt(environment.getProperty("elasticsearch.port")));
client.addTransportAddress(address);        
return client;
}

    @Beanpublic ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchTemplate(client());
     }
}


You put elasticsearch host and post in your application properties file.

elasticsearch.host = localhost
 # if you use you local elasticsearch host
elasticsearch.port = 9300


3. Data mapping object: 

In this application, we have 2 entities data object mapping: Post and Tag

@Document(indexName = "post", type = "post", shards = 1, replicas = 0)
public class Post {
@Idprivate String id;    private String title;// 
@Field(type= FieldType.Nested)
private List<Tag> tags;   
 public String getId() {
        return id;
}

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

    public String getTitle() {
        return title;
}

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

    public List<Tag> getTags() {
        return tags;
}

    public void setTags(List<Tag> tags) {
        this.tags = tags;}
}


public class Tag {
 private String id;   
 private String name;   
 public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
  }
}

4. Repository: we extends from ElasticsearchRepository

public interface PostRepository extends ElasticsearchRepository<Post, String>{

    Page<Post> findByTagsName(String name, Pageable pageable);
}


5. Data access service

public interface PostService {
    Post save(Post post);
    Post findOne(String id);
    Iterable<Post> findAll();
    Page<Post> findByTagsName(String tagName, PageRequest pageRequest);
}


@Servicepublic class PostServiceImpl implements PostService{
    @Autowired
private PostRepository postRepository;
@Override
public Post save(Post post) {
        postRepository.save(post);        

              return post;
       }

    @Overridepublic Post findOne(String id) {
        return postRepository.findOne(id);
   }

    @Overridepublic Iterable<Post> findAll() {
        return postRepository.findAll();
   }

    @Overridepublic Page<Post> findByTagsName(String tagName, PageRequest pageRequest) {
        return postRepository.findByTagsName(tagName, pageRequest);
   }
}

6. Testing and the result

@Testpublic void testFindByTagsName() throws Exception {
Tag tag = new Tag();
tag.setId("1");
tag.setName("tech");
Tag tag2 = new Tag();
tag2.setId("2");
tag2.setName("elasticsearch");
Post post = new Post();
post.setId("1");
post.setTitle("Bigining with spring boot application and elasticsearch");
post.setTags(Arrays.asList(tag, tag2));
postService.save(post);
Post post2 = new Post();
post2.setId("1");
post2.setTitle("Bigining with spring boot application");
post2.setTags(Arrays.asList(tag));
postService.save(post);
Page<Post> posts  = postService.findByTagsName("tech", new PageRequest(0,10));Page<Post> posts2  = postService.findByTagsName("tech", new PageRequest(0,10));Page<Post> posts3  = postService.findByTagsName("maz", new PageRequest(0,10));assertThat(posts.getTotalElements(), is(1L));
assertThat(posts2.getTotalElements(), is(1L));
assertThat(posts3.getTotalElements(), is(0L));
}

7. You can find detail project at github: https://github.com/herotl2005/spring-data-elasticsearch-sample

The Integration Zone is brought to you in partnership with 3scale. Learn how API providers have changed the way we think about integration in The Platform Vision of API Giants.

转载地址:https://dzone.com/articles/first-step-spring-boot-and

Spring Boot整合Elasticsearch的步骤如下: 1. 首先,在pom.xml文件中导入spring-boot-starter-data-elasticsearch依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 这个依赖会自动引入Elasticsearch的相关库。 2. 然后,在项目的配置文件application.properties或application.yml中设置Elasticsearch的连接地址,比如: ``` spring.elasticsearch.rest.uris=http://localhost:9200 ``` 这里将Elasticsearch连接地址设置为本地的9200端口。 3. 接下来,在代码中使用ElasticsearchRestTemplate来进行操作。可以通过@Autowired注解将ElasticsearchRestTemplate注入到需要使用的类中,比如: ```java @SpringBootTest class Springboot18EsApplicationTests { @Autowired private ElasticsearchRestTemplate template; } ``` 这样就可以使用template对象来进行Elasticsearch的操作了。 总结一下,整合Spring BootElasticsearch的步骤包括导入依赖、配置连接地址和使用ElasticsearchRestTemplate进行操作。可以参考引用和引用中提供的代码和依赖信息,以及引用中的下载和参考链接获取更详细的信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [SpringBoot整合ES](https://blog.csdn.net/m0_37294838/article/details/127235741)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [springboot+ES](https://blog.csdn.net/weixin_41945912/article/details/125541243)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值