SpringBoot整合ElasticSearch实战入门

                                         SpringBoot整合ElasticSearch实战入门

第一部分:通读文档

Spring Data Elasticsearch 官方文档,这是当前最新的文档。

例子1:开始就介绍了CrudRepository这个接口类,功能就是管理的实体类复杂的CRUD功能。

SpringBoot整合ElasticSearch实战入门_第1张图片

 

例子2:PagingAndSortingRepository添加了其他方法来简化对实体的分页处理。

SpringBoot整合ElasticSearch实战入门_第2张图片

还有例子,进行分页查询和其他查询。

SpringBoot整合ElasticSearch实战入门_第3张图片

SpringBoot整合ElasticSearch实战入门_第4张图片

现在主要关注的是:ElasticsearchRepository,已经提供了大部分的功能接口。

SpringBoot整合ElasticSearch实战入门_第5张图片

/**
 * @param 
 * @param 
 * @author Rizwan Idrees
 * @author Mohsin Husen
 * @author Sascha Woo
 * @author Murali Chevuri
 */
@NoRepositoryBean
public interface ElasticsearchRepository extends ElasticsearchCrudRepository {

	 S index(S entity);

	/**
	 * This method is intended to be used when many single inserts must be made that cannot be aggregated to be inserted
	 * with {@link #saveAll(Iterable)}. This might lead to a temporary inconsistent state until {@link #refresh()} is
	 * called.
	 */
	 S indexWithoutRefresh(S entity);

	Iterable search(QueryBuilder query);

	Page search(QueryBuilder query, Pageable pageable);

	Page search(SearchQuery searchQuery);

	Page searchSimilar(T entity, String[] fields, Pageable pageable);

	void refresh();

	Class getEntityClass();
}

第二部分:整合部分

2.1、添加依赖

implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'

implementation 'com.alibaba:fastjson:1.2.62'//JSON支持

2.2、添加配置,和springboot整合ok

spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.cluster-name=es-wyf

2.3、编码

import com.alibaba.fastjson.annotation.JSONField;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

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

//indexName相当于数据库
//type相当于数据中的表
@Document(indexName = "user", type = "java")
public class User implements Serializable {

    @Id
    private String id;

    private String username;

    private String password;

    private String nickname;

    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    private Date time;


    public String getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }
}
public interface UserRepository extends ElasticsearchRepository {

    //自定义的方法,可以find,根据提示,自动出来查询语句
    public List findUserByUsernameIsLike(String keyword);

}

 

import com.alibaba.fastjson.JSON;
import com.example.demo.domain.User;
import com.example.demo.repository.UserRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController {

    private Log LOGGER = LogFactory.getLog(UserController.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    //@todo 添加数据
    @RequestMapping(value = "/add")
    public String add(@RequestBody User user) {
        return JSON.toJSONString(userRepository.save(user));
    }

    //@todo 查询所有
    @RequestMapping(value = "/all")
    public String all() {
        Iterable iterable = userRepository.findAll();
        List list = new ArrayList<>();
        iterable.forEach(list::add);
        return JSON.toJSONString(list);
    }

    //@todo ID查询
    @RequestMapping(value = "/get/{id}")
    public String get(@PathVariable String id) {
        Optional optional = userRepository.findById(id);
        if (optional.isPresent()) {
            return JSON.toJSONString(optional.get());
        }
        return JSON.toJSONString("fail");
    }

    //@todo 更新数据
    @RequestMapping(value = "/update")
    public String update(@RequestBody User user) {
        return JSON.toJSONString(userRepository.save(user));
    }

    //@todo 删除数据
    @RequestMapping(value = "/delete/{id}")
    public String update(@PathVariable String id) {
        userRepository.deleteById(id);
        return all();
    }

    //@todo 模糊查询
    @RequestMapping(value = "/find/username")
    public String find(String username) {
        return JSON.toJSONString(userRepository.findUserByUsernameIsLike(username));
    }

    //@todo 全文检索 分页查询
    @RequestMapping(value = "/search/all")
    public String page(Integer page, Integer size, String keyword) {
        Pageable pageable = PageRequest.of(page, size);
        QueryBuilder queryBuilder = new QueryStringQueryBuilder(keyword);
        Page pResult = userRepository.search(queryBuilder, pageable);
        LOGGER.info("list:" + JSON.toJSONString(pResult.getContent()));
        LOGGER.info("pages:" + JSON.toJSONString(pResult.getTotalPages()));
        LOGGER.info("total:" + JSON.toJSONString(pResult.getTotalElements()));
        return JSON.toJSONString(pResult.getContent());
    }
    
}

SpringBoot整合ElasticSearch实战入门_第6张图片添加数据:

SpringBoot整合ElasticSearch实战入门_第7张图片

SpringBoot整合ElasticSearch实战入门_第8张图片

查询所有: 

 

 SpringBoot整合ElasticSearch实战入门_第9张图片

根据ID查询: 

 SpringBoot整合ElasticSearch实战入门_第10张图片

根据ID更新: 

 

 

SpringBoot整合ElasticSearch实战入门_第11张图片

SpringBoot整合ElasticSearch实战入门_第12张图片

根据字段检索: 

 

 SpringBoot整合ElasticSearch实战入门_第13张图片

 

SpringBoot整合ElasticSearch实战入门_第14张图片

 全文检索分页:

SpringBoot整合ElasticSearch实战入门_第15张图片

SpringBoot整合ElasticSearch实战入门_第16张图片

SpringBoot整合ElasticSearch实战入门_第17张图片

 

你可能感兴趣的:(SpringBoot学习笔记)