spring boot 如何集成 elasticsearch

一、前言

本篇博客将讲解三种spring boot集成elasticsearch的方法

  1. REST Client
  2. Jest
  3. Spring Data Elasticsearch Repositories

二、Spring Data Elasticsearch Repositories方式

1、引入pom依赖

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  </dependency>

2、增加配置

在application.properties文件中增加如下配置

spring.data.elasticsearch.repositories.enabled = true
spring.data.elasticsearch.cluster-nodes = 127.0.0.1:9300

也许,大家会疑惑,明明elsaticsearch的端口是9200,为何这里配置文件中连接的时候写的端口是9300呢?

因为,配置9200是通过HTTP连接的端口,9300是TCP连接的端口

3、实体类

package com.tp.demo.entity;

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

/**
 * @Package: com.tp.demo
 * @ClassName: Product
 * @Author: tanp
 * @Description: 类比关系型数据库的话,Index索引相当于数据库,type类比比表,Document文档相当于表里的一行记录
 * @Date: 2020/9/22 17:19
 */
@Data
@Document(indexName = "product",type = "doc")
public class Product {
    @Id
    private int id;
    @Field(type = FieldType.Text)
    private String name;

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + "]";
    }
}

注意:indexName索引值首字母必须小写

4、继承ElasticsearchRepository

新建一个接口继承ElasticsearchRepository实现跟elasticsearch服务器交互

package com.tp.demo.repository;

import com.tp.demo.entity.Product;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

/**
 * @Package: com.tp.demo.repository
 * @ClassName: ProductRepository
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/9/23 9:29
 */
@Repository
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {
}

5、新增service接口和实现类

ProductService
package com.tp.demo.service;

import com.tp.demo.entity.Product;

import java.util.List;

/**
 * @Package: com.tp.demo.service
 * @ClassName: ProductService
 * @Author: tanp
 * @Description: 使用Elasticsearch Repositories的方式进行增删改查
 * @Date: 2020/9/23 9:25
 */
public interface ProductService {
    /**
     * @Description 保存文档
     * @Date 2020/9/30 11:32
     * @Author tanp
     */
    int saveProduct(Product product);

    /**
     * @Description 删除文档
     * @Date 2020/9/30 11:32
     * @Author tanp
     */
    void deleteProduct(Product product);

    /**
     * @Description 修改文档
     * @Date 2020/9/30 11:35
     * @Author tanp
     */
    int updateProduct(Product product);

    /**
     * @Description 查询文档数据
     * @Date 2020/9/30 14:15
     * @Author tanp
     */
    List<Product> searchProduct(Integer pageNum, Integer pageSize, String searchName);

    /**
     * @Description 查询所有文档
     * @Date 2020/9/30 15:40
     * @Author tanp
     */
    List<Product> getAllProduct();

    void deleteAllProduct();

    void createIndex();

    void deletIndex();
}
ProductServiceImpl
package com.tp.demo.service.impl;

import com.tp.demo.entity.Product;
import com.tp.demo.repository.ProductRepository;
import com.tp.demo.service.ProductService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
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.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

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

/**
 * @Package: com.tp.demo.service.impl
 * @ClassName: ProductServiceImpl
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/9/23 9:26
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductRepository productRepository;

    @Autowired
    private ElasticsearchTemplate template;

    @Override
    public int saveProduct(Product product) {
        Product productResult = productRepository.save(product);
        return productResult.getId();
    }

    @Override
    public void deleteProduct(Product product) {
        productRepository.delete(product);
    }

    @Override
    public int updateProduct(Product product) {
        Product product1 = productRepository.save(product);
        return product1.getId();
    }

    @Override
    public List<Product> searchProduct(Integer pageNum, Integer pageSize, String searchName) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        QueryBuilder queryBuilder = QueryBuilders.matchPhraseQuery("name", searchName);
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(queryBuilder).build();
        Page<Product> products = productRepository.search(searchQuery);
        return products.getContent();
    }

    @Override
    public List<Product> getAllProduct() {
        Iterable<Product> products = productRepository.findAll();
        List<Product> productList = new ArrayList<>();
        for (Product product : products) {
            productList.add(product);
        }
        return productList;
    }

    @Override
    public void deleteAllProduct() {
        productRepository.deleteAll();
    }

    @Override
    public void createIndex() {
        template.createIndex("product5");
    }

    @Override
    public void deletIndex() {
        template.deleteIndex("product5");
    }
}

6、新增对外暴露的接口类

ProductController
package com.tp.demo.controller;

import com.tp.demo.entity.Product;
import com.tp.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Package: com.tp.demo.controller
 * @ClassName: ProductController
 * @Author: tanp
 * @Description: Spring Data Elasticsearch Repositories方式保存文档数据,无需对索引进行操作,
 * 因为Product实体类上的@Document注解已经指定好了所以,当保存数据时,就会默认创建索引,
 * 索引就像是数据库,我们平时是不会是通过java代码的去创建修改删除数据库,我们只会针对数据做CRUD的操作
 * @Date: 2020/9/23 9:23
 */
@RestController
public class ProductController {

    @Autowired
    ProductService productService;


    /**
     * @Description 创建索引,不推荐直接在java代码中对索引进行操作
     * @Date 2020/10/12 11:31
     * @Author tanp
     */
    @RequestMapping(value = "/product/createIndex")
    public void  createIndex(){
        productService.createIndex();
    }

    /**
     * @Description  删除索引
     * @Date 2020/10/12 11:32
     * @Author tanp
     */
    @RequestMapping(value = "/product/deleteIndex")
    public void deleteIndex(){
        productService.deletIndex();
    }

    /**
     * @Description 保存文档
     * @Date 2020/9/30 11:29
     * @Author tanp
     */
    @RequestMapping(value = "/product/save", method = RequestMethod.POST)
    public int saveProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }

    /**
     * @Description 删除文档
     * @Date 2020/9/30 11:37
     * @Author tanp
     */
    @RequestMapping(value = "/product/delete", method = RequestMethod.GET)
    public void deleteProduct(@RequestBody Product product) {
        productService.deleteProduct(product);
    }

    /**
     * @Description 修改文档
     * @Date 2020/9/30 11:38
     * @Author tanp
     */
    @RequestMapping(value = "/product/update", method = RequestMethod.GET)
    public int updateProduct(@RequestBody Product product) {
        return productService.updateProduct(product);
    }

    /**
     * @Description 查询文档
     * @Date 2020/9/30 11:41
     * @Author tanp
     */
    @RequestMapping(value = "/product/search", method = RequestMethod.POST)
    public List<Product> searchProduct(@RequestParam(value = "pageNum") Integer pageNum,
                                       @RequestParam(value = "pageSize") Integer pageSize,
                                       @RequestParam(value = "searchName") String searchName) {
        return productService.searchProduct(pageNum, pageSize, searchName);
    }

    /**
     * @Description 查询全部文档
     * @Date 2020/10/10 10:20
     * @Author tanp
     */
    @RequestMapping(value = "product/getAll",method = RequestMethod.GET)
    public List<Product> getAllProduct(){
        return productService.getAllProduct();

    }


    /**
     * @Description 删除所有文档数据
     * @Date 2020/10/9 10:45
     * @Author tanp
     */
    @RequestMapping(value = "product/deleteAll",method = RequestMethod.GET)
    public void deleteAllProduct(){
        productService.deleteAllProduct();
    }

}

注意:controll使用@RequestBody注解时发送请求时contentType需要为application/json;

对索引的curd,对文档的curd,都可直接访问;http://127.0.0.1:9200/_cat/indices?v 

查看对索引,文档的操作结果

三、jest方式

1、引入pom依赖

 <dependency>
     <groupId>io.searchbox</groupId>
     <artifactId>jest</artifactId>
 </dependency>
 <dependency>
     <groupId>net.java.dev.jna</groupId>
     <artifactId>jna</artifactId>
 </dependency>

2、增加配置

application.properties中增加如下配置

spring.elasticsearch.jest.uris= http://127.0.0.1:9200

3、实体类

package com.tp.demo.entity;

import io.searchbox.annotations.JestId;
import lombok.Data;

import java.io.Serializable;

/**
 * @Package: com.tp.demo.entity
 * @ClassName: Product1
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/9/30 17:25
 */
@Data
public class Product1 implements Serializable {
    //@JestId注解一定要加上,表示该实体的主键是id,否则后续以id查询删除时会有问题
    @JestId
    private String id;
    private String name;

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + "]";
    }
}

注意:对于作为id的属性一定记得加注解@JestId

4、service接口和实现类

ProductService1
package com.tp.demo.service;

import com.tp.demo.entity.Product1;

import java.io.IOException;
import java.util.List;

/**
 * @Package: com.tp.demo.service
 * @ClassName: ProductService1
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/9/30 16:05
 */
public interface ProductService1 {

    void saveProduct(Product1 product);

    void saveProducts(List<Product1> productList);

    List<Product1> searchProduct(String searchContent);

    boolean deleteProduct(String id) throws IOException;

    boolean createIndex(String indexName) throws IOException;

    String getIndexMapping(String indexName,String typeName) throws IOException;

    boolean deleteIndex(String indexName) throws IOException;

    boolean closeIndex(String indexName) throws IOException;

    boolean openIndex(String indexName) throws IOException;

    boolean hasIndex(String indexName) throws IOException;


    Product1 getProductById(String id) throws IOException;


    boolean updateProduct(Product1 product) throws IOException;
}
ProductService1Impl
package com.tp.demo.service.impl;

import com.tp.demo.entity.Product1;
import com.tp.demo.service.ProductService1;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import io.searchbox.indices.*;
import io.searchbox.indices.mapping.GetMapping;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @Package: com.tp.demo.service.impl
 * @ClassName: ProductService1Impl
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/9/30 16:12
 */
@Service
public class ProductService1Impl implements ProductService1 {

    @Autowired
    private JestClient jestClient;

    @Override
    public void saveProduct(Product1 product) {
        Index index = new Index.Builder(product).index("product1").type("doc1").build();
        try {
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveProducts(List<Product1> productList) {
        Bulk.Builder bulk = new Bulk.Builder();
        for (Product1 product : productList) {
            Index index = new Index.Builder(product).index("product1").type("doc1").build();
            bulk.addAction(index);
        }
        try {
            jestClient.execute(bulk.build());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Product1> searchProduct(String searchContent) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("name", searchContent));
        Search search = new Search.Builder(searchSourceBuilder.toString())
                .addIndex("product1").addType("doc1").build();
        try {
            JestResult result = jestClient.execute(search);
            return result.getSourceAsObjectList(Product1.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean deleteProduct(String id) throws IOException {
        Delete index = new Delete.Builder(id).index("product1").type("doc1").build();
        DocumentResult dr = jestClient.execute(index);
        System.out.println(dr.getJsonString());
        return dr.isSucceeded();
    }

    @Override
    public boolean createIndex(String indexName) throws IOException {
        CreateIndex index = new CreateIndex.Builder(indexName).build();
        JestResult jestResult = jestClient.execute(index);
        return jestResult.isSucceeded();
    }

    @Override
    public String getIndexMapping(String indexName, String typeName) throws IOException {
        GetMapping getMapping = new GetMapping.Builder().addIndex(indexName).addType(typeName).build();
        JestResult jestResult = jestClient.execute(getMapping);
        return jestResult.getJsonString();
    }

    @Override
    public boolean deleteIndex(String indexName) throws IOException {
        DeleteIndex index = new DeleteIndex.Builder(indexName).build();
        JestResult jestResult = jestClient.execute(index);
        return jestResult.isSucceeded();
    }

    @Override
    public boolean closeIndex(String indexName) throws IOException {
        CloseIndex closeIndex = new CloseIndex.Builder(indexName).build();
        JestResult jestResult = jestClient.execute(closeIndex);
        return jestResult.isSucceeded();
    }

    @Override
    public boolean openIndex(String indexName) throws IOException {
        OpenIndex openIndex = new OpenIndex.Builder(indexName).build();
        JestResult jestResult = jestClient.execute(openIndex);
        return jestResult.isSucceeded();
    }

    @Override
    public boolean hasIndex(String indexName) throws IOException {
        IndicesExists indicesExists = new IndicesExists.Builder(indexName).build();
        JestResult jestResult = jestClient.execute(indicesExists);
        return jestResult.isSucceeded();
    }


    @Override
    public Product1 getProductById(String id) throws IOException {
        Get get = new Get.Builder("product1", id).type("doc1").build();
        JestResult jestResult = jestClient.execute(get);
        return jestResult.getSourceAsObject(Product1.class);
    }

    @Override
    public boolean updateProduct(Product1 product) throws IOException {
        Update index = new Update.Builder(product).index("product1").type("doc1").build();
        JestResult jestResult = jestClient.execute(index);
        return jestResult.isSucceeded();
    }
}

5、对外暴露的controller接口

package com.tp.demo.controller;

import com.tp.demo.entity.Product1;
import com.tp.demo.service.ProductService1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @Package: com.tp.demo.controller
 * @ClassName: ProductController1
 * @Author: tanp
 * @Description: jest方式进行文档类增删改查, 本类演示了对索引的一些基本操作,实际生产中不推荐在java文件里对索引进行操作
 * @Date: 2020/9/30 15:53
 */
@RestController
public class ProductController1 {

    @Autowired
    ProductService1 productService1;

    /**
     * @Description 创建索引,
     * @Date 2020/10/9 17:41
     * @Author tanp
     */
    @RequestMapping(value = "/createIndex")
    public boolean createIndex(String indexName) {
        try {
            return productService1.createIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * @Description 删除索引
     * @Date 2020/10/10 9:08
     * @Author tanp
     */
    @RequestMapping(value = "/deleteIndex")
    public boolean deleteIndex(String indexName) {
        try {
            return productService1.deleteIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @Description 关闭索引
     * @Date 2020/10/10 9:34
     * @Author tanp
     */
    @RequestMapping(value = "/closeIndex")
    public boolean closeIndex(String indexName) {
        try {
            return productService1.closeIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @Description 打开索引
     * @Date 2020/10/10 9:35
     * @Author tanp
     */
    @RequestMapping(value = "/openIndex")
    public boolean openIndex(String indexName) {
        try {
            return productService1.openIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * @Description 查询索引
     * @Date 2020/10/10 9:03
     * @Author tanp
     */
    @RequestMapping(value = "/getIndexMapping")
    public String getIndexMapping(String indexName, String typeName) {
        try {
            return productService1.getIndexMapping(indexName, typeName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @Description 索引是否存在
     * @Date 2020/10/10 9:53
     * @Author tanp
     */
    @RequestMapping(value = "/hasIndex")
    public boolean hasIndex(String indexName) {
        try {
            return productService1.hasIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @Description 保存文档
     * @Date 2020/10/9 16:57
     * @Author tanp
     */
    @RequestMapping(value = "/product1/save", method = RequestMethod.POST)
    public String save(@RequestBody Product1 product) {
        productService1.saveProduct(product);
        return "OK";
    }

    /**
     * @Description 全文搜索文档
     * @Date 2020/10/9 16:58
     * @Author tanp
     */
    @RequestMapping(value = "/product1/search", method = RequestMethod.GET)
    public List<Product1> search(String name) {
        return productService1.searchProduct(name);
    }

    /**
     * @Description 批量保存文档数据
     * @Date 2020/10/9 16:58
     * @Author tanp
     */
    @RequestMapping(value = "product1/batchSave", method = RequestMethod.POST)
    public String batchSave(@RequestBody List<Product1> products) {
        productService1.saveProducts(products);
        return "ok";
    }


    /**
     * @Description 单个删除文档数据
     * @Date 2020/10/9 16:58
     * @Author tanp
     */
    @RequestMapping(value = "/product1/delete", method = RequestMethod.GET)
    public boolean deleteProduct(String id) {
        try {
            return productService1.deleteProduct(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * @Description 通过主键id获取文档数据
     * @Date 2020/10/10 10:40
     * @Author tanp
     */
    @RequestMapping(value = "/product1/getProductById", method = RequestMethod.GET)
    public Product1 getProductById(String id) {
        try {
            return productService1.getProductById(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Product1();
    }


    /**
     * @Description 更新文档数据
     * @Date 2020/10/10 11:26
     * @Author tanp
     */
    @RequestMapping(value = "/product1/update", method = RequestMethod.POST)
    public boolean updateProduct(@RequestBody Product1 product) {
        try {
            return productService1.updateProduct(product);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

四、REST Client方式

1、引入pom依赖

        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.2.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>6.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.2.0</version>
        </dependency>

2、新增配置

es:
  host: 192.169.1.167
  port: 9200
  scheme: http

3、创建实体

package com.demo;

import lombok.Data;

/**
 * @Package: com.tp.demo.entity
 * @ClassName: Product
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/9/30 17:25
 */
@Data
public class Product {
    private String id;
    private String name;

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + "]";
    }
}

4、创建service接口和是实现类

ProductService2
package com.demo;

import java.io.IOException;
import java.util.List;

/**
 * @Package: com.tp.demo.service
 * @ClassName: ProductService2
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/10/10 16:18
 */
public interface ProductService2 {

    void createIndex(String indexName) throws IOException;

    boolean hasIndex(String indexName) throws IOException;

    void deleteIndex(String indexName) throws IOException;

    void saveProduct(Product product) throws IOException;

    void saveProducts(List<Product> products) throws IOException;

    String getProductById(String id) throws IOException;

    void updateProduct(Product product) throws IOException;

    void deleteProduct(String id) throws IOException;


    List<String> searchProduct(Integer pageNum, Integer pageSize, String searchName) throws IOException;

}
ProductService2Impl
package com.demo;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.tp.demo.service.impl
 * @ClassName: ProductService2Impl
 * @Author: tanp
 * @Description: ${description}
 * @Date: 2020/10/10 16:19
 */
@Service
public class ProductService2Impl implements ProductService2 {

    @Autowired
    RestHighLevelClient client;

    @Override
    public void createIndex(String indexName) throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        client.indices().create(createIndexRequest);
    }

    @Override
    public boolean hasIndex(String indexName) throws IOException {
        boolean result = true;
        try {
            OpenIndexRequest openIndexRequest = new OpenIndexRequest(indexName);
            client.indices().open(openIndexRequest).isAcknowledged();
        } catch (ElasticsearchStatusException ex) {
            String m = "Elasticsearch exception [type=index_not_found_exception, reason=no such index]";
            if (m.equals(ex.getMessage())) {
                result = false;
            }
        }
        return result;
    }

    @Override
    public void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        client.indices().delete(deleteIndexRequest);
    }

    @Override
    public void saveProduct(Product product) throws IOException {
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("name", product.getName());
        IndexRequest indexRequest = new IndexRequest("product2","doc2",product.getId()).source(jsonMap);
        client.index(indexRequest);
    }

    @Override
    public void saveProducts(List<Product> products) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for(Product product : products){
            Map<String,Object> map = new HashMap();
            map.put("name",product.getName());
            IndexRequest indexRequest = new IndexRequest("product2","doc2",product.getId()).source(map);
            bulkRequest.add(indexRequest);
        }
        client.bulk(bulkRequest);
    }

    @Override
    public String getProductById(String id) throws IOException {
        GetRequest getRequest = new GetRequest("product2","doc2",id);
        GetResponse getResponse = client.get(getRequest);
        return getResponse.getSourceAsString();
    }

    @Override
    public void updateProduct(Product product) throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("product2","doc2",product.getId()).doc("name",product.getName());
        client.update(updateRequest);
    }

    @Override
    public void deleteProduct(String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("product2","doc2",id);
        client.delete(deleteRequest);
    }

    @Override
    public List<String> searchProduct(Integer pageNum, Integer pageSize, String searchName) throws IOException {
        SearchRequest searchRequest = new SearchRequest("product2");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name",searchName);
        searchSourceBuilder.query(matchQueryBuilder);
        //第几页
        searchSourceBuilder.from(pageNum);
        //第几条
        searchSourceBuilder.size(pageSize);
        searchRequest.source(searchSourceBuilder);
        //匹配度从高到低
        searchSourceBuilder.sort(new ScoreSortBuilder().order(SortOrder.DESC));
        SearchResponse searchResponse = client.search(searchRequest);
        SearchHits searchHits = searchResponse.getHits();
        SearchHit[] searchHits1 = searchHits.getHits();
        List<String> names = new ArrayList<>();
        String name;
        for(SearchHit searchHit: searchHits1){
            name = searchHit.getSourceAsString();
            names.add(name);
        }
        return names;
    }

}

5、对外暴露controller

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package: com.tp.demo.controller
 * @ClassName: ProductController2
 * @Author: tanp
 * @Description: REST Client集成Elasticsearch,进行相关的操作
 * @Date: 2020/10/10 16:15
 */
@RestController
public class ProductController2 {

    @Autowired
    ProductService2 productService2;

    /**
     * @Description 创建索引
     * @Date 2020/10/10 16:21
     * @Author tanp
     */

    @RequestMapping(value = "product2/createIndex")
    public void createIndex(String indexName) {
        try {
            productService2.createIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 判断索引是否存在
     * @Date 2020/10/10 16:39
     * @Author tanp
     */
    @RequestMapping(value = "product2/hasIndex")
    public boolean hasIndex(String indexName) {
        try {
            return productService2.hasIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @Description 删除索引
     * @Date 2020/10/10 16:41
     * @Author tanp
     */
    @RequestMapping(value = "product2/deleteIndex")
    public void deleteIndex(String indexName) {
        try {
            productService2.deleteIndex(indexName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description 保存文档数据
     * @Date 2020/10/10 17:33
     * @Author tanp
     */
    @RequestMapping(value = "/product2/save", method = RequestMethod.POST)
    public void saveProduct(@RequestBody Product product) {
        try {
            productService2.saveProduct(product);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @Description 批量保存
     * @Date 2020/10/10 17:35
     * @Author tanp
     */
    @RequestMapping(value = "product2/batchSave",method = RequestMethod.POST)
    public String batchSave(@RequestBody List<Product> products){
        try {
            productService2.saveProducts(products);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

    /**
     * @Description 通过id获取文档数据
     * @Date 2020/10/12 9:28
     * @Author tanp
     */
    @RequestMapping(value = "/product2/getProductById", method = RequestMethod.GET)
    public String getProductById(String id){
        try {
            return productService2.getProductById(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "nothing";
    }

    /**
     * @Description 修改文档数据
     * @Date 2020/10/12 9:42
     * @Author tanp
     */
    @RequestMapping(value = "/product2/update", method = RequestMethod.POST)
    public boolean updateProduct(@RequestBody Product product) {
        try {
            productService2.updateProduct(product);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * @Description 通过id删除文档数据
     * @Date 2020/10/12 9:48
     * @Author tanp
     */
    @RequestMapping(value = "/product2/delete", method = RequestMethod.GET)
    public boolean deleteProduct(String id) {
        try {
            productService2.deleteProduct(id);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * @Description 全文搜索文档
     * @Date 2020/10/12 9:59
     * @Author tanp
     */
    @RequestMapping(value = "/product2/search", method = RequestMethod.POST)
    public List<String> searchProduct(@RequestParam(value = "pageNum") Integer pageNum,
                                       @RequestParam(value = "pageSize") Integer pageSize,
                                       @RequestParam(value = "searchName") String searchName) {
        try {
            return productService2.searchProduct(pageNum, pageSize, searchName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }


}

五、总结

本片博客中都是基于elasticsearch6.62版本的,新版本中的一些接口请求参数会有些改变,但是拿来作为入门学习还是可以的

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值