Spring Boot 集成 elasticsearch

一、Spring Boot 集成 elasticsearch

配置文件pom.xml:

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

配置文件application.properties:

# elasticsearch集群名称,默认的是elasticsearch
spring.data.elasticsearch.cluster-name=elasticsearch
##配置ES的访问地址
#节点的地址 注意api模式下端口号是9300,千万不要写成9200
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300

二、elasticsearch在Spring Boot中的测试代码

ElasticSearchController文件代码如下:

package com.example.shopgoods.controller.elasticsearch;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: zp
 * @Date: 2019/6/14 11:31
 * @Description:
 */
@RestController
@RequestMapping("/es")
public class ElasticSearchController {

    @Autowired
    private BookDao bookDao;


    /**
     * springboot原生调用elasticsearch
     * @param id
     * @return
     */
    @PostMapping("/book/{id}")
    public String getBookById(@PathVariable String id){
        Book book = null;
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://127.0.0.1:9200/product/book/{id}";
        Map map = new HashMap();
        map.put("id", id);
        String str = restTemplate.getForObject(url, String.class, map);
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory jsonFactory = mapper.getFactory();
        try {
            JsonParser jsonParser = jsonFactory.createParser(str);
            JsonNode jsonNode = mapper.readTree(jsonParser);
            JsonNode sourceNode = jsonNode.get("_source");
            book = mapper.convertValue(sourceNode, Book.class);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return book.toString();
    }


    /**
     * springboot通过spring data来集成elasticsearch
     * @param id
     * @return
     */
    @PostMapping("/bookEntity/{id}")
    public String getBookEntityById(@PathVariable String id){
        // CrudRepository内置的查询
        Optional<BookEntity> opt = bookDao.findById(id);
        BookEntity bookEntity = opt.get();
        return bookEntity.toString();
    }

    @PostMapping("/bookEntityAllList")
    public List<BookEntity> getList(@RequestParam(value = "key") String key){
        List<BookEntity> bookEntities = bookDao.getByMessage(key);
        return bookEntities;
    }


    @PostMapping("/bookEntityListOfPage")
    public List<BookEntity> getListOfPage(@RequestParam(value = "key") String key,
                                          @RequestParam(value = "page") int page,
                                          @RequestParam(value = "pageSize") int pageSize){

        //分页查询
        PageRequest pageRequest = PageRequest.of(page, pageSize);

        Page<BookEntity> bookEntityPage = bookDao.getByMessage(key, pageRequest);
        Long totle = bookEntityPage.getTotalElements();
        Integer totlePage = bookEntityPage.getTotalPages();
        List<BookEntity> bookEntities = bookEntityPage.getContent();

        return bookEntities;
    }



}

Book文件代码如下:

package com.example.shopgoods.controller.elasticsearch;

import lombok.Data;

import java.util.Date;

/**
 * @Author: zp
 * @Date: 2019/6/14 11:30
 * @Description:
 */
@Data
public class Book {
    private String name;
    private String type;
    private Date postDate;
    private String message;

}

BookDao文件代码如下:

package com.example.shopgoods.controller.elasticsearch;

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

import java.io.Serializable;
import java.util.Date;

/**
 * @Author: zp
 * @Date: 2019/6/14 11:30
 * @Description:
 */
@Data
@Document(indexName = "product", type = "book")
public class BookEntity implements Serializable {

    private String id;
    private String name;
    private String type;
    private Date postDate;
    private String message;

}

BookEntity文件代码如下:

package com.example.shopgoods.controller.elasticsearch;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: zp
 * @Date: 2019/6/14 14:32
 * @Description:
 */

@Component
public interface BookDao extends ElasticsearchRepository<BookEntity, String> {

    /**
     * 模糊匹配,类似sql中的where message like '%{key}%'
     * @param key
     * @return
     */
    public List<BookEntity> getByMessage(String key);

    public Page<BookEntity> getByMessage(String key, Pageable pageable);
}

参考文献:

1.SpringBoot集成Elasticsearch并进行增删改查操作

2.spring data elasticsearch的 @Documnet 和 @Field 注解

答疑参考:

1.Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]

2.(转)Elasticsearch NoNodeAvailableException None of the configured nodes are available

3.elasticsearch.bat闪退的解决方案
(如果elasticsearch.bat闪退,还可以通过windows系统的cmd命令,进入elasticsearch.bat目录,通过命令执行如图:
在这里插入图片描述

4.springBoot集成Elasticsearch 报错 Health check failed

5.关于spring-data-elasticsearch使用出现的一些小问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值