1、创建一个maven项目

项目结构:
在这里插入图片描述

2、导入依赖

<dependencies>
    <!--  测试用  -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--  主要  -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-elasticsearch</artifactId>
      <version>4.1.5</version>
    </dependency>
    <!--  测试用  -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!--  小辣椒  -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.20</version>
      <scope>compile</scope>
    </dependency>
    <!--  日志  -->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-to-slf4j</artifactId>
      <version>2.13.3</version>
    </dependency>
  </dependencies>

3、添加spring配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/data/elasticsearch
       http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd">
    <!--es  dao扫描-->
    <elasticsearch:repositories base-package="com.hdit"></elasticsearch:repositories>
    <!--配置es client-->
    <elasticsearch:rest-client id="client"  hosts="http://192.168.184.128:9201,http://192.168.184.128:9202,http://192.168.184.128:9203"></elasticsearch:rest-client>

    <!--es template-->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate">
        <constructor-arg name="client"  ref="client"></constructor-arg>
    </bean>
</beans>

4、编写实体类映射

package com.hdit.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
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;

/**
 * @基本功能:
 * @ClassName: User
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/30 11:15
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
//文档映射:indexName索引库名称,indexStoreType索引类型名称
@Document(indexName = "hdit", indexStoreType = "users")
public class User {
    // @Id表示主键字段
    @Id
//    index该字段是否进行分词,store是否存储,type字段数据类型
//    searchAnalyzer搜索分词器,analyzer存储分词器
    @Field(index = true, store = true, type = FieldType.Integer)
    private Integer id;
    @Field(index = true, store = true, type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
    private String name;
    @Field(index = false, store = true, type = FieldType.Integer)
    private Integer age;
    @Field(index = true, store = true, type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
    private String sex;
}

5、编写dao接口

package com.hdit.dao;

import com.hdit.domain.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

/**
 * @基本功能:
 * @ClassName: UserDao
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/30 11:14
 * @Version 1.0
 */
public interface UserDao extends ElasticsearchRepository<User,Integer> {
//  (1)方式一,使用父接口的方法进行查询,dao接口不用写。
//******************************************************************/
//  (2)方式二,使用特定命名规则的自定义方法,如下所示:
    User findByName(String name);
    User findByNameAndId(String name,Integer id);
    List<User> findBySexOrderByAgeDesc(String sex);
    List<User> findBySexOrderByIdDesc(String sex, Pageable p);
/******************************************************************/
// (3)方式三,高级查询searcher方法,dao接口不用写。
//******************************************************************/
// (4)方式四,使用@Query注解,如下所示:
    @Query("{\"term\":{\"sex\":\"?0\"}}")
    List<User>   queryUsers (String  sex);
}

6、测试

(1)方式一,使用父接口的方法进行查询。

package com.hdit.test;

import com.hdit.dao.UserDao;
import com.hdit.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Optional;

/**
 * @基本功能:
 * @ClassName: EsTest
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/30 11:19
 * @Version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-es.xml")
public class QueryTest01 {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Autowired
    private UserDao userDao;

    @Test
    public   void   test1(){
//        创建索引库
        elasticsearchTemplate.createIndex("hdit");

//        创建映射
        elasticsearchTemplate.putMapping(User.class);

    }
    @Test
    public void testAdd(){
        User user = new User();
        user.setId(2020003);
        user.setName("李嘉明03");
        user.setAge(24);
        user.setSex("男");
        User save = userDao.save(user);
        System.out.println(save);
    }
    @Test
    public void testFindAll(){
        Iterable<User> users = userDao.findAll();
        users.forEach(user-> System.out.println(user));
    }
    @Test
    public void testFindUserById(){
        Optional<User> user = userDao.findById(2020001);
        User user1 = user.get();
        System.out.println(user);
        System.out.println(user1);
    }
}

(2)方式二,使用特定命名规则的自定义方法。

package com.hdit.test;

import com.hdit.dao.UserDao;
import com.hdit.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
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.domain.Sort;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.Optional;

/**
 * @基本功能:
 * @ClassName: QueryTest
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/30 16:14
 * @Version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-es.xml")
public class QueryTest02 {

    @Autowired
    private UserDao userDao;

    @Test
    public void queryAll() {
        Iterable<User> all = userDao.findAll();
        for (User user : all) {
            System.out.println(user);
        }
    }

    @Test
    public void queryById() {
        Optional<User> byId = userDao.findById(1);
        User user = byId.get();
        System.out.println(user);
    }

    @Test
    public void queryByPage() {
        Pageable p = PageRequest.of(2, 3);
        Page<User> all = userDao.findAll(p);
        for (User user : all) {
            System.out.println(user);
        }
    }


    @Test
    public void queryBySort() {
        Sort sort = Sort.by(Sort.Order.desc("age"));
        Iterable<User> all = userDao.findAll(sort);
        for (User user : all) {
            System.out.println(user);
        }
    }

    @Test
    public void queryByPageAndSort() {
        Pageable p = PageRequest.of(0, 3, Sort.by(Sort.Order.desc("age")));
        Page<User> all = userDao.findAll(p);
        for (User user : all) {
            System.out.println(user);
        }
    }
    @Test
    public void queryByName(){
        User user = userDao.findByName("李嘉明");
        System.out.println(user);
    }
    @Test
    public void queryByNameAndId(){
        User user = userDao.findByNameAndId("李嘉明",2020001);
        System.out.println(user);
    }
    @Test
    public void queryBySexOrderByAgeDesc(){
        List<User> users = userDao.findBySexOrderByAgeDesc("男");
        users.forEach(user -> System.out.println(user));
    }
    @Test
    public void queryBySexOrderByIdDesc(){
        Pageable p = PageRequest.of(0,2);
        List<User> users = userDao.findBySexOrderByIdDesc("男",p);
        users.forEach(user -> System.out.println(user));
    }

}

(3)方式三,高级查询searcher方法。

package com.hdit.test;

import com.hdit.dao.UserDao;
import com.hdit.domain.User;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
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.domain.Sort;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.Optional;

/**
 * @基本功能:
 * @ClassName: QueryTest
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/30 16:14
 * @Version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-es.xml")
public class QueryTest03 {

    @Autowired
    private UserDao userDao;
    
    @Test
    public void query01(){
        TermQueryBuilder builder = QueryBuilders.termQuery("sex","男");
        Iterable<User> users = userDao.search(builder);
        users.forEach(user -> System.out.println(user));
    }
    @Test
    public void query02(){
        TermQueryBuilder builder = QueryBuilders.termQuery("age",22);
        Iterable<User> users = userDao.search(builder);
        users.forEach(user -> System.out.println(user));
    }
}

(4)方式四,使用@Query注解

package com.hdit.test;

import com.hdit.dao.UserDao;
import com.hdit.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;

/**
 * @基本功能:
 * @ClassName: QueryTest
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/30 16:14
 * @Version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-es.xml")
public class QueryTest04 {

    @Autowired
    private UserDao userDao;

    @Test
    public void query1() {
        List<User> users = userDao.queryUsers("男");
        for (User user : users) {
            System.out.println(user);
        }
    }
}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐