整合Spring data elasticsearch 2021/5/24

使用Java代码操作elasticsearch

•搭建环境
•索引和映射操作
•数据操作(增删改)
•查询

创建Demo工程

我们新建一个test-elasticsearch 编写Elasticsearch

pom依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>changgou4-parent-ali</artifactId>
        <groupId>com.czxy.changgou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>test-elasticsearch</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>
配置工具类
package com.czxy.changgou4.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;


@Configuration
@EnableElasticsearchRepositories
public class RestClientConfig extends AbstractElasticsearchConfiguration {
    
    

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
    
    

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}
启动类
package com.czxy.changgou4;

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


@SpringBootApplication
public class TestESApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(TestESApplication.class,args);
    }
}
测试类
package com.czxy.changgou4;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestElasticsearchApplication.class)
public class TestES {
    
    

    @Test
    public void testDemo() {
    
    
        System.out.println("....");
    }
}

创建索引和映射

实体类:首先我们准备好实体类:
public class Item {
    
    
    		private Long id;
    		private String title; 			//标题
    		private String category;		//分类
    		private String brand; 			//品牌
    		private Double price; 			//价格
   		private String images; 		//图片地址
}
映射

Spring Data通过注解来声明字段的映射属性,有下面的三个注解:

•@Document 作用在类,标记实体类为文档对象,一般有两个属性
–indexName:对应索引库名称
–type:对应在索引库中的类型
–shards:分片数量,默认5
–replicas:副本数量,默认1

•@Id 作用在成员变量,标记一个字段作为id主键
•@Field 作用在成员变量,标记为文档的字段,并指定字段映射属性:

–type:字段类型,是是枚举:FieldType
–index:是否索引,布尔类型,默认是true
–store:是否存储,布尔类型,默认是false
–analyzer:分词器名称

示例:

@Document(indexName = "item",type = "docs", shards = 1, replicas = 0)
public class Item {
    
    
    @Id
    private Long id;
    
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String title; //标题
    
    @Field(type = FieldType.Keyword)			//不分词
    private String category;// 分类
    
    @Field(type = FieldType.Keyword)
    private String brand; // 品牌
    
    @Field(type = FieldType.Double)
    private Double price; // 价格
    
    @Field(index = false, type = FieldType.Keyword)
    private String images; // 图片地址
}
创建索引
package com.czxy;

import com.czxy.changgou4.TestESApplication;
import com.czxy.changgou4.domain.Item;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestESApplication.class)
public class TestES {
    
    

    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Test
    public void testCreateIndex() {
    
    
        elasticsearchTemplate.createIndex(Item.class);
    }
}

数据操作

查询

1.基本查询
  @Test
    public void testFindAll() {
    
    
        // 查询所有
        Iterable<Item> list = itemRepository.findAll();
        list.forEach(System.out::println);
    }

    @Test
    public void testFindAllSort() {
    
    
        // 查询所有--排序   ascending升序  descending降序
        Iterable<Item> list = itemRepository.findAll(Sort.by("price").ascending());
        list.forEach(System.out::println);
    }

    @Test
    public void testFindById() {
    
    
        Optional<Item> optional = itemRepository.findById(20L);
        if(optional.isPresent()) {
    
    
            Item item = optional.get();
            System.out.println(item);
        } else {
    
    
            System.out.println("没有结果");
        }
    }
2.自定义方法查询

•编写repository

 package com.czxy.changgou4.repository;

import com.czxy.changgou4.domain.Item;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;


public interface ItemRepository extends ElasticsearchRepository<Item,Long> {
    
    


    /**
     * 查询标题
     * @param title
     * @return
     */
    public List<Item> findByTitle(String title);

    /**
     * 范围查询
     * @param startPrice
     * @param endPrice
     * @return
     */
    public List<Item> findByPriceBetween(Double startPrice, Double endPrice);
}

•测试

@Test
public void testFindByTitle() {
    
    
    List<Item> list = itemRepository.findByTitle("手机");
    list.forEach(System.out::println);
}

@Test
public void testFindByPriceBetween() {
    
    
    List<Item> list = itemRepository.findByPriceBetween(3000d,4000d);
    list.forEach(System.out::println);
}
 

感谢看到现在 拜拜~~~~

猜你喜欢

转载自blog.csdn.net/LiGuanLink/article/details/117231686