SpringBoot 集成 ElasticSearch 实现模糊搜索

实验环境

  • ES 版本:5.6.15

  • Spring Boot 版本:2.0.5.RELEASE

首先当然需要安装好 Elastic Search 环境 

Spring工程创建 

添加maven依赖

        <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>io.searchbox</groupId>
            <artifactId>jest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>

项目的配置文件application.yml

spring:
  elasticsearch:
    jest:
      uris: http://192.168.56.101:9200/
      read-timeout: 5000

 代码组织

 

各部分代码详解如下:

Entity.java

package com.example.esdemo.entity;

import lombok.Data;

import java.io.Serializable;

/**
 * @author 杨红杰
 * @date 2021/2/9 13:59
 */
@Data
public class Entity implements Serializable {
    public static final String INDEX_NAME = "index_entity";
    public static final String TYPE = "tstype";

    private Long id;
    private String name;

    public Entity(Long id, String name) {
        this.id = id;
        this.name = name;
    }
}

TestService.java

package com.example.esdemo.service;

import com.example.esdemo.entity.Entity;

import java.util.List;

/**
 * @author 杨红杰
 * @date 2021/2/9 14:00
 */
public interface TestService {
    void saveEntity(Entity entity);

    void saveEntity(List<Entity> entityList);

    List<Entity> searchEntity(String searchContent);
}

 TestServiceImpl.java

 

package com.example.esdemo.service.impl;

import com.example.esdemo.entity.Entity;
import com.example.esdemo.service.TestService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import lombok.extern.slf4j.Slf4j;
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;

/**
 * @author 杨红杰
 * @date 2021/2/9 14:01
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private JestClient jestClient;

    @Override
    public void saveEntity(Entity entity) {
        Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
        try {
            jestClient.execute(index);
            log.info("ES 插入完成");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 批量保存内容到ES
     * @param entityList
     */
    @Override
    public void saveEntity(List<Entity> entityList) {
        Bulk.Builder bulk = new Bulk.Builder();
        for(Entity entity : entityList) {
            Index index = new Index.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();
            bulk.addAction(index);
        }

        try {
            jestClient.execute(bulk.build());
            log.info("ES 插入完成");
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 在ES中搜索内容
     * @param searchContent
     * @return
     */
    @Override
    public List<Entity> searchEntity(String searchContent) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));
        Search search = new Search.Builder(searchSourceBuilder.toString())
                .addIndex(Entity.INDEX_NAME).addType(Entity.TYPE).build();
        try {
            JestResult result = jestClient.execute(search);
            return result.getSourceAsObjectList(Entity.class);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }
}

EntityController.java

package com.example.esdemo.controller;

import com.example.esdemo.entity.Entity;
import com.example.esdemo.service.TestService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @author 杨红杰
 * @date 2021/2/9 14:06
 */
@RestController
@RequestMapping("/entityController")
public class EntityController {
    @Autowired
    TestService testService;

    @GetMapping("/save")
    public String save(long id, String name) {
        System.out.println("save 接口");
        if(id>0 && StringUtils.isNotEmpty(name)) {
            Entity newEntity = new Entity(id, name);
            List<Entity> addList = new ArrayList<>();
            addList.add(newEntity);
            testService.saveEntity(addList);
            return "OK";
        }else {
            return "Bad input value";
        }
    }

    @GetMapping("/search")
    public List<Entity> save(String name) {
        List<Entity> entityList = null;
        if(StringUtils.isNotEmpty(name)) {
            entityList = testService.searchEntity(name);
        }
        return entityList;
    }
}

实际实验

增加几条数据,可以使用postman工具,也可以直接在浏览器中输入,如增加以下5条数据:

  1. http://localhost:8080/entityController/save?id=1&name=太原迎泽公园

  2. http://localhost:8080/entityController/save?id=2&name=太原理工大学

  3. http://localhost:8080/entityController/save?id=3&name=太原柳巷

  4. http://localhost:8080/entityController/save?id=4&name=晋中也非常不错

  5. http://localhost:8080/entityController/save?id=5&name=山西太原很美

数据插入效果如下 

我们来做一下搜索的测试:例如我要搜索关键字“太原” 我们在浏览器中输入:

 

 

刚才插入的5条记录中包含关键字“太原”的四条记录均被搜索出来了!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值