美文网首页
ElasticSearch入门

ElasticSearch入门

作者: 程序员Darker | 来源:发表于2019-09-30 08:38 被阅读0次

1. 步骤分析

  1. 创建maven项目
  2. 导包
  3. 配置yml
  4. 入口类
  5. 测试
  6. 创建索引+做类型映射
  7. crud
  8. 高级查询+分页+排序(DSL)

2. 步骤实现

2.1 创建maven项目

略过

2.2 导包

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/>
    </parent>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--springboot 对spring data es支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

2.3 配置yml

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300 #9200是图形界面端,9300代码端

2.4 入口类

package cn.wangningbo.es;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ESApplication {
    public static void main(String[] args) {
        SpringApplication.run(ESApplication.class, args);
    }
}

2.5 测试

package cn.wangningbo.es;

import cn.wangningbo.es.doc.Employee;
import cn.wangningbo.es.repository.EmployeeDocRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ESApplication.class)
public class ESTest {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 先测试ElasticsearchTemplate是否可以注入进来
     *
     * @throws Exception
     */
    @Test
    public void test() throws Exception {
        System.out.println(elasticsearchTemplate);
    }
}

2.6 创建索引+做类型映射

  1. 运行ElasticSearch服务
  2. 准备映射
package cn.wangningbo.es.doc;

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;

@Document(indexName = "hrm_test", type = "employee")
public class Employee {
    @Id
    private Long id;
    @Field(type = FieldType.Keyword)//不会分词建立索引
    private String name;
    private Integer age;
    @Field(type = FieldType.Text)//分词建立索引
    private String intro;
    //模糊查询所有字段 //投机-有空格就会分词
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String all; //把keyword要作用的字段,通过空格来拼接
    
    //提供get、set、构造、toString方法
}
  1. 执行下面这个测试方法(创建索引+做类型映射)
    /**
     * 创建索引并做类型映射
     * @throws Exception
     */
    @Test
    public void testPre() throws Exception {
        elasticsearchTemplate.createIndex(Employee.class);
        elasticsearchTemplate.putMapping(Employee.class);
    }

2.7 crud

准备

package cn.wangningbo.es.repository;

import cn.wangningbo.es.doc.Employee;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface EmployeeDocRepository extends ElasticsearchRepository<Employee, Long> {
}

crud操作

    @Autowired
    private EmployeeDocRepository employeeDocRepository;
    
        /**
     * 添加一个
     *
     * @throws Exception
     */
    @Test
    public void testAdd() throws Exception {
        Employee employee = new Employee(1L, "tom", 18, "温顺的猫咪!");
        employee.setAll(employee.getName() + " " + employee.getIntro());
        employeeDocRepository.save(employee);
    }

    /**
     * 添加多个
     *
     * @throws Exception
     */
    @Test
    public void testAddAll() throws Exception {
        List<Employee> employees = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            Employee employee = new Employee(2L + i, "tom" + i, 19 + i, "温顺的猫咪!" + i);
            employees.add(employee);
        }
        employeeDocRepository.saveAll(employees);
    }

    /**
     * 查询一个(根据id)
     *
     * @throws Exception
     */
    @Test
    public void testFindOne() throws Exception {
        System.out.println(employeeDocRepository.findById(2l).get());
    }

    /**
     * 查询所有
     *
     * @throws Exception
     */
    @Test
    public void testFindAll() throws Exception {
        Iterable<Employee> employees = employeeDocRepository.findAll();
        employees.forEach(employee -> System.out.println(employee));
    }

    /**
     * 删除一个(根据id)
     *
     * @throws Exception
     */
    @Test
    public void testDelete() throws Exception {
        employeeDocRepository.deleteById(1l);
    }

    /**
     * 修改一个(修改同添加!id存在就是修改,不存在就是添加)
     *
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        Employee employee = employeeDocRepository.findById(2l).get();
        employee.setName("杰瑞");
        employeeDocRepository.save(employee);
    }

2.8 高级查询+分页+排序(DSL)

    @Autowired
    private EmployeeDocRepository employeeDocRepository;

    /**
     * dsl(高级查询+分页+排序)
     *
     * @throws Exception
     */
    @Test
    public void testDSL() throws Exception {
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //封装查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        List<QueryBuilder> must = boolQueryBuilder.must();
        must.add(QueryBuilders.matchAllQuery());
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        filter.add(QueryBuilders.rangeQuery("age").gte(20).lte(40));
        //查询
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        //排序    //根据age字段进行升序排序
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.ASC));
        //分页    //page:0就是第1页,size:10就是每页显示10条
        nativeSearchQueryBuilder.withPageable(PageRequest.of(0, 10));
        //截取字段  //前面是需要显示的字段,后面是排除的字段
        nativeSearchQueryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "name", "age"}, null));
        //封装结果
        Page<Employee> search = employeeDocRepository.search(nativeSearchQueryBuilder.build());
        //获取所有元素个数
        long totalElements = search.getTotalElements();
        //遍历查看所有元素
        search.forEach(employee -> System.out.println(employee));
    }

相关文章

网友评论

      本文标题:ElasticSearch入门

      本文链接:https://www.haomeiwen.com/subject/sylcpctx.html