Es-SpringData

赤叶秋枫發表於2024-06-25

String-Data

  1. 建立專案,設定包名com.cn.es
  2. 引入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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cn.es</groupId>
    <artifactId>es-spring</artifactId>
    <version>1.0</version>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.6.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.7.13</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>



建立application.properties

#esIP地址
elasticsearch.host=127.0.0.1
#es埠號碼
elasticsearch.port=9200
#設定日誌級別為debug
logging.level.com.cn.es=debug


建立啟動類

package com.cn.es;

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

@SpringBootApplication
public class SpringDataEsMainApplication {

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

}


建立ES的配置類

package com.cn.es.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

@Data
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
    private String host ;
    private Integer port ;

    @Override
    public RestHighLevelClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}


建立實體類

package com.cn.es.domain;

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

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Document(indexName = "product",shards = 3,replicas = 1)
public class Product {

    @Id
    private Long id;//商品唯一標識
    @Field(type = FieldType.Text)
    private String title;//商品名稱
    //不做分詞處理
    @Field(type = FieldType.Keyword)
    private String category;//分類名稱
    @Field(type = FieldType.Double)
    private Double price;//商品價格
    //不做分詞處理,不做索引關聯,不能透過索引路徑查詢
    @Field(type = FieldType.Keyword,index = false)
    private String images;//圖片地址

}


建立DAO層

package com.cn.es.dao;

import com.cn.es.domain.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductDao extends ElasticsearchRepository<Product,Long> {

}


建立test類查詢:

package com.cn.es.test;

import com.cn.es.dao.ProductDao;
import com.cn.es.domain.Product;
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.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataProductDaoTest {

    @Autowired
    private ProductDao productDao;

    /**
     * 新增任務
     */
    @Test
    public void save () {
        Product product = new Product();
        product.setId(2L);
        product.setTitle("華為手機");
        product.setCategory("手機");
        product.setPrice(2999.0);
        product.setImages("http://hw.jpg");
        productDao.save(product);
    }

    //相同id就是更新
    @Test
    public void update () {
        Product product = new Product();
        product.setId(2L);
        product.setTitle("小米手機");
        product.setCategory("手機");
        product.setPrice(29999.0);
        product.setImages("http://xm.jpg");
        productDao.save(product);
    }


    @Test
    public void findById(){
        Product product = productDao.findById(2L).get();
        System.out.println(product);
    }


    @Test
    public void findAll(){
        Iterable<Product> products = productDao.findAll();
        for (Product product : products)
        {
            System.out.println(product);
        }
    }

    @Test
    public void delete(){
       Product product=new Product();
       product.setId(1L);
       productDao.delete(product);
    }


    //批次新增
    @Test
    public void saveAll(){
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Product product = new Product();
            product.setId(Long.valueOf(i));
            product.setTitle("[" + i + "]小米手機");
            product.setCategory("手機");
            product.setPrice(1999.0 + i);
            product.setImages("http://www.xm.jpg");
            productList.add(product);
        }
    }
    
    
/**
term查詢
search(termQueryBuilder)呼叫搜尋方法,引數查詢構建器物件
*/

@Test
public void termQuery(){
    
    TermQueryBuilder termQueryBuilder=QueryBuilders.termsQuery("title","小米");
    Iterable<Product> pros = productDao.search(termQueryBuilder);
    for(Product product:pros){
        System.out,printLn(product);
    }
    
}
    
    
    
    
/**
term查詢,分頁查詢
*/
@Test
public void termQueryByPage(){
    int currentPage=0;
    int pageSize=5;
    //設定查詢分頁
    PageRequest pageRequest = PageRequest.of(currentPage,pageSize);
    TermQueryBuilder termQueryBuilder = QueryBuilders.termsQuery("category","小米");
    Iterable<Product> pros = productDao.search(termQueryBuilder,pageRequest);
    for(Product product:pros){
        System.out,println(product);
    }
    
}


}