SpringBoot之对Elastic Search进行CRUD等操作

一、概念

Elastic Search是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。

Elastic Search是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

二、使用方式

使用的方式主要两种:

① 一种是经过 SpringData 封装过的,直接在类似 dao 接口继承 ElasticsearchRepository 即可,如下:

public interface dataToEsRepository extends ElasticsearchRepository {
}

② 一种是经过 Spring 封装过的,直接在 Service/Controller 中引入该 bean 即可,即,ElasticsearchTemplate elasticsearchTemplate;

三、SpringBoot集成Elastic Search

方式一:接口继承 ElasticsearchRepository

1. pom依赖引入



     org.springframework.boot
     spring-boot-starter-data-elasticsearch
     2.1.2.RELEASE

2. 配置相关文件

#ES配置
spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch #elasticsearch集群名称,默认的是elasticsearch
      cluster-nodes: 127.0.0.1:9300 #节点的地址 注意api模式下端口号是9300,千万不要写成9200
      repositories:
        enabled: true #是否开启本地存储

3. 索引对应的实体类

package com.stu.elasticsearch.dto;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
 
/**
 * Created with IntelliJ IDEA
 *
 * @author codeBoy
 * @version V1.0.0
 * @since 2019-01-13 下午2:49
 * To change this template use File | Settings | File Templates.
 */
@Document(indexName = "department",type = "staff", shards = 1,replicas = 0, refreshInterval = "-1")
public class Staff {
    @Id
    private String id;
    @Field
    private String firstName;
    @Field
    private String lastName;
    @Field
    private Integer age = 0;
    @Field
    private String about;
 
    public String getId() {
        return id;
    }
 
    public void setId(String id) {
        this.id = id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public String getAbout() {
        return about;
    }
 
    public void setAbout(String about) {
        this.about = about;
    }
}

4. 实体类对应的dao接口


package com.stu.elasticsearch.repository;
 
import com.elasticsearch.entity.Employee;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA
 *
 * @author codeBoy
 * @version V1.0.0
 * @since 2019-01-13 下午2:55
 * To change this template use File | Settings | File Templates.
 */
@Component
public interface StaffRepository extends ElasticsearchRepository{
 
    /**
     * 根据ID 查询员工信息
     *
     * @param id id
     * @return Staff
     */
    Staff queryStaffById(String id);
}

5. service层调用

package com.stu.elasticsearch.service;
import com.stu.elasticsearch.repository.StaffRepository;
import com.stu.elasticsearch.dto.staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.highlight.HighlightBuilder;
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.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
 
/**
 * Created with IntelliJ IDEA
 *
 * @author codeBoy
 * @version V1.0.0
 * @since 2019-01-13 下午3:05
 * To change this template use File | Settings | File Templates.
 */
@Service
public class StaffService {
 
    @Autowired
    private StaffRepository staffRepository;
 
    /**
     * 新增员工测试
     *
     * @return String
     */
    public String saveStaff() {
        Staff staff = new Staff();
        staff.setId("1");
        staff.setFirstName("xuxu");
        staff.setLastName("zh");
        staff.setAge(26);
        staff.setAbout("Beijing");
        staffRepository.save(staff);
        return "success";
    }
 
    /**
     * 删除测试
     * 
     * @return
     */
    public String delete() {
        Staff staff = staffRepository.queryStaffeById("1");
        staffRepository.delete(staff);
        return "success";
    }
 
    /**
     * 更新
     * @return
     */
    public String update() {
        Staff staff = staffRepository.queryStaffById("1");
        staff.setFirstName("宋");
        staffRepository.save(staff);
        return "success";
    }
    /**
     * 查询
     * @return
     */
    public Staff query() {
        Staff staff = staffRepository.queryStaffById("1");
        return staff;
    }

   /**
     *  带分页、权重、分域查询
     * @param page 分页
     * @param size  个数
     * @param keyWord 关键字
     * @return staff集合
     */
    public List searchStaffInfoByKeyWord(Integer page, Integer size, String keyWord) {

        // 分页参数
        Pageable pageable = new PageRequest(page, size);

        // 分数,并自动按分排序
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
                .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("firstName", keyWord)),
                        ScoreFunctionBuilders.weightFactorFunction(1000)) // 权重:firstName 1000分
                .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("lastName", keyWord)),
                        ScoreFunctionBuilders.weightFactorFunction(100)); // 权重:lastName 100分

        // 分数、分页
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable)
                .withQuery(functionScoreQueryBuilder).build();

        Page searchPageResults = staffRepository.search(searchQuery);
        return searchPageResults.getContent();
    }
}  

方式二:使用ElasticsearchTemplate

service代码如下:

package com.stu.elasticsearch.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
 
/**
 * Created with IntelliJ IDEA
 *
 * @author codeBoy
 * @version V1.0.0
 * @since 2019-01-13 下午3:15
 * To change this template use File | Settings | File Templates.
 */
@Service
public class StaffNewService {
 
    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
 
   
   /**
     *  获取所有的员工
     * @return staff集合
     */
    public List> searchAllStaff() {

        //这一步是最关键的
        Client client = elasticsearchTemplate.getClient();
        // @Document(indexName = "department", type = "staff")
        SearchRequestBuilder srb = client.prepareSearch("department").setTypes("staff");
        SearchResponse sr = srb.setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); // 查询所有
        SearchHits hits = sr.getHits();
        List> list = new ArrayList>();
        for (SearchHit hit : hits) {
            Map source = hit.getSource();
            list.add(source);
            System.out.println(hit.getSourceAsString());
        }
        return list;
    }
}  

你可能感兴趣的:(SpringBoot之对Elastic Search进行CRUD等操作)