springboot 集成 elasticsearch(maven项目)

1.搭建springboot项目,能跑起来(具体百度,我的springboot版本 1.5.9.RELEASE)

2.本机或者服务器安装elasticsearch并启动服务成功(我本地Windows安装的elasticsearch版本6.1.1)

3.pom引入依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>
<dependency>
    <groupId>net.java.dev.jnagroupId>
    <artifactId>jnaartifactId>
    <version>4.5.1version>
dependency>

3.配置文件添加 application.properties


# ELASTICSEARCH (ElasticsearchProperties})
#集群名。(默认值: elasticsearch)
spring.data.elasticsearch.cluster-name=elasticsearch
#集群其他节点地址列表,用逗号分隔。如果没有指定,就启动一个客户端节点。默认 9300 是 Java 客户端的端口。
#spring.data.elasticsearch.cluster-nodes=192.168.21.111:9300
#是否开启本地(我本地测试用就启用本地了)
spring.data.elasticsearch.local=true
#开启 Elasticsearch 仓库。(默认值:true。)
spring.data.elasticsearch.repositories.enabled=true
#存储索引的位置
#spring.data.elasticsearch.properties.path.home=data/elasticsearch
#日志存储目录
#spring.data.elasticsearch.properties.path.logs=./elasticsearch/log
#数据存储目录
#spring.data.elasticsearch.properties.path.data=./elasticsearch/data
#连接超时的时间
#spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s

4.实体对象添加注解

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

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

@Document(indexName="user",type="user")
public class User implements Serializable {
    @Id
    private Integer id;
    //类型改成string存到elasticsearch
    @Field(type = FieldType.String)
    private Long mobile;

    private String password;

    private String nickname;

    getter setter...
    }

5.ElasticsearchRepository已实现 保存 删除等直接调用就行

import cc.datebook.springboot.entity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

import java.util.List;

//泛型的参数分别是实体类型和主键类型
@Component
public interface UserSearchRepository extends ElasticsearchRepository<User, Integer> {

    List findUserByMobileContainingOrNicknameContaining(String mobile,String nickname);
}

6.接口调用

@PostMapping(value = "/user")
    public JsonResult user(@RequestBody Map<String, Object> params) {
        String keyword = params.get("keyword").toString();
        List<User> users = UserSearchRepository.findUserByMobileContainingOrNicknameContaining(keyword,keyword);
        Map<String,Object> map =  new HashMap<String,Object>();
        map.put("users", users);
        return new JsonResult(ResultCode.SUCCESS, "检测成功",map);
    }

你可能感兴趣的:(springboot,elasticsearch)