ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

整合Spring data elasticsearch 2021/5/24

2021-05-24 21:01:44  阅读:89  来源: 互联网

标签:24 Spring springframework elasticsearch private import org public


使用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);
}
 

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

标签:24,Spring,springframework,elasticsearch,private,import,org,public
来源: https://blog.csdn.net/LiGuanLink/article/details/117231686

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有