springboot 整合 elasticsearch

1引入jar包

  

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

2实体类

package com.miracle.config.elasticsearch.entity;

import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;

import java.io.Serializable;

/**
 * Coding makes me happy.
 *  ┏┓   ┏┓
 * ┏┛┻━━━┛┻┓
 * ┃  ☆☆☆  ┃
 * ┃   ━   ┃
 * ┃ ┳┛ ┗┳ ┃
 * ┃       ┃
 * ┃   ┻   ┃
 * ┗━┓ 史 ┏━┛
 *   ┃ 诗 ┃神兽保佑
 *   ┃ 之 ┃代码无BUG!
 *   ┃ 宠 ┗━━━┓
 *   ┃Author:   ┣┓
 *   ┃    liu.Q ┏┛
 *   ┗┓┓┏━┳┓┏┛
 *    ┃┫┫ ┃┫┫
 *    ┗┻┛ ┗┻┛
 * ----------------------
 *
 * @Date : 2018/3/7 下午2:35
 * @Description :elasticsearch 商品信息库
 */
@Data
@Document(indexName = "goodsindex",type = "goods")
//indexName索引名称 可以理解为数据库名 必须为小写 不然会报org.elasticsearch.indices.InvalidIndexNameException异常
//type类型 可以理解为表名
public class GoodsInfo implements Serializable {
    private int id; //商品规格id
    private int goods_id;//商品id
    private String goods_name;//商品名称
    private String goods_sku_name;//商品规格名称
    private String goods_class_code;//商品分类编号
    private String goods_class_name;//商品分类名称
    private double price;//价格
    private int sales_num;//销量(初始销量+真实销量)
    private int stock;//库存

    private String description;//搜索关键字逗号(,)分隔 ==(分类名称,商品名称,规格名称)

    public GoodsInfo() {
    }

    public GoodsInfo(int id, int goods_id, String goods_name, String goods_sku_name, String goods_class_code, String goods_class_name, double price, int sales_num, int stock, String description) {
        this.id = id;
        this.goods_id = goods_id;
        this.goods_name = goods_name;
        this.goods_sku_name = goods_sku_name;
        this.goods_class_code = goods_class_code;
        this.goods_class_name = goods_class_name;
        this.price = price;
        this.sales_num = sales_num;
        this.stock = stock;
        this.description = description;
    }
}

3接口

package com.miracle.config.elasticsearch.service;

import com.miracle.config.elasticsearch.entity.GoodsInfo;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

/**
 * Coding makes me happy.
 *  ┏┓   ┏┓
 * ┏┛┻━━━┛┻┓
 * ┃  ☆☆☆  ┃
 * ┃   ━   ┃
 * ┃ ┳┛ ┗┳ ┃
 * ┃       ┃
 * ┃   ┻   ┃
 * ┗━┓ 史 ┏━┛
 *   ┃ 诗 ┃神兽保佑
 *   ┃ 之 ┃代码无BUG!
 *   ┃ 宠 ┗━━━┓
 *   ┃Author:   ┣┓
 *   ┃    liu.Q ┏┛
 *   ┗┓┓┏━┳┓┏┛
 *    ┃┫┫ ┃┫┫
 *    ┗┻┛ ┗┻┛
 * ----------------------
 *
 * @Date : 2018/3/7 下午2:35
 * @Description :商品信息 接口
 */
@Component
public interface GoodsRepository extends ElasticsearchRepository<GoodsInfo,Long> {
}

4 controller测试

package com.miracle.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.miracle.config.elasticsearch.entity.GoodsInfo;
import com.miracle.config.elasticsearch.service.GoodsRepository;
import com.miracle.config.redis.RedisService;
import com.miracle.controller.wx.util.AesCbcUtil;
import com.miracle.controller.wx.util.WXUtil;
import com.miracle.mapper.WxUserMapper;
import com.miracle.model.WxUser;
import com.miracle.util.ReturnVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.print.Book;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Coding makes me happy.
 *  ┏┓   ┏┓
 * ┏┛┻━━━┛┻┓
 * ┃  ☆☆☆  ┃
 * ┃   ━   ┃
 * ┃ ┳┛ ┗┳ ┃
 * ┃       ┃
 * ┃   ┻   ┃
 * ┗━┓ 史 ┏━┛
 *   ┃ 诗 ┃神兽保佑
 *   ┃ 之 ┃代码无BUG!
 *   ┃ 宠 ┗━━━┓
 *   ┃Author:   ┣┓
 *   ┃    liu.Q ┏┛
 *   ┗┓┓┏━┳┓┏┛
 *    ┃┫┫ ┃┫┫
 *    ┗┻┛ ┗┻┛
 * ----------------------
 *
 * @Date : 2018/3/7 下午2:35
 * @Description :elasticsearch测试
 */
@Slf4j
@EnableTransactionManagement  // 需要事务的时候加上
@RestController
@Api("elasticsearch测试")
@RequestMapping("/wx")
public class ElasticsearchTestController {

    @Autowired
    private GoodsRepository goodsRepository;

    @ApiOperation(value = "添加/更新", notes = "id一样即可实现更新")
    @RequestMapping(value="/save",method = RequestMethod.GET)
    public String save(@ModelAttribute GoodsInfo goodsInfo){
        goodsRepository.save(goodsInfo);
        return "success";
    }

    @ApiOperation(value = "搜索", notes = "搜索")
    @RequestMapping(value="/getList",method = RequestMethod.GET)
    public List<GoodsInfo> searchCity(@ApiParam(name = "s",value = "关键字",defaultValue = "商品") String s) {
        //创建builder  minimumShouldMatch - 匹配到次数
        QueryBuilder builder = QueryBuilders.multiMatchQuery(s,"goods_name").minimumShouldMatch(s.length()+"");

        //builder下有must、should以及mustNot 相当于sql中的and、or以及not
        //设置模糊搜索,multiMatchQuery 匹配多字段
//        builder.must(QueryBuilders.multiMatchQuery(s,"goods_name"));
//          builder.must(QueryBuilders.termQuery(s,"goods_name"));
//        builder.should(QueryBuilders.matchQuery("description", s));
        //模糊查询
//        builder.should(QueryBuilders.fuzzyQuery("goods_name", s));
        //设置名称为商品
//        builder.must(new QueryStringQueryBuilder("商品").field("goods_name"));

        //排序
        FieldSortBuilder sort = SortBuilders.fieldSort("id").order(SortOrder.DESC);

        //设置分页
        //====注意!es的分页和Hibernate一样api是从第0页开始的=========
        PageRequest pageRequest = new PageRequest(0, 10);

        //构建查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //将搜索条件设置到构建中
        nativeSearchQueryBuilder.withQuery(builder);
        //将分页设置到构建中
        nativeSearchQueryBuilder.withPageable(pageRequest);
        //将排序设置到构建中
        nativeSearchQueryBuilder.withSort(sort);
        //生产NativeSearchQuery
        NativeSearchQuery query = nativeSearchQueryBuilder.build();

        //执行,返回包装结果的分页
        Page<GoodsInfo> resutlList = goodsRepository.search(query);
        return resutlList.getContent();
    }

    @ApiOperation(value = "查询全部", notes = "查询全部")
    @RequestMapping(value="/getAll",method = RequestMethod.GET)
    public List<GoodsInfo> searchCity() {
        //构建查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //生产NativeSearchQuery
        NativeSearchQuery query = nativeSearchQueryBuilder.build();
        //执行,返回包装结果的分页
        Page<GoodsInfo> resutlList = goodsRepository.search(query);

        return resutlList.getContent();
    }
    @ApiOperation(value = "删除全部", notes = "删除全部")
    @RequestMapping(value="/deleteAll",method = RequestMethod.GET)
    public String deleteAll() {
        goodsRepository.deleteAll();
        return "success";
    }
}

5  官方api参考地址

https://www.elastic.co/guide/en/elasticsearch/client/java-api/5.5/java-full-text-queries.html

原文地址:https://www.cnblogs.com/liuq1991/p/9444509.html

时间: 2024-10-08 05:57:44

springboot 整合 elasticsearch的相关文章

SpringBoot整合ElasticSearch实现多版本的兼容

前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和SpringBoot进行结合使用. ElasticSearch介绍 ElasticSearch是一个基于Lucene的搜索服务器,其实就是对Lucene进行封装,提供了 REST API 的操作接口 ElasticSearch作为一个高度可拓展的开源全文搜索和分析引擎,可用于快速地对大数据进行存储,搜索和分析.

SpringBoot整合elasticsearch(三)

Docker安装elasticsearch 启动注意2点,1是内存,2是线程数(此处进行简单安装,后面会详细补充es文档) 1 [[email protected] ~]# docker images 2 REPOSITORY TAG IMAGE ID CREATED SIZE 3 elasticsearch latest 874179f19603 12 days ago 771 MB 4 springbootdemo4docker latest cd13bc7f56a0 2 weeks ago

SpringBoot整合Elasticsearch框架

新建SpringBoot项目: 修改pom.xml文件,引入spring-boot-data-elasticsearch Jar 包: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> <version>2.2.2.RELEASE</ver

【SpringBoot整合Elasticsearch】SpringBoot整合ElasticSearch

一.Linux下安装ElasticSearch 1.检测是否安装了Elasticsearch 1 ps aux |grep elasticsearch 2.安装JDK 3.下载Elasticsearch 1 wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.0.0.tar.gz 解压Elasticsearch tar -zxvf elasticsearch-6.0.0.tar.gz 移动Elasti

springboot整合elasticsearch遇到的错误

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.2018-12-29 11:54:39.572 ERROR 7563 --- [ main] o.s.boot.SpringApplication : Application startup failed org.springframework.beans.

SpringBoot整合ElasticSearch

1.docker安装ElasticSearch ps:前提是电脑必须安装好java并配置好环境变量 从远程仓库拉取镜像 docker pull elasticsearch:6.8.0 由于es需要的内存比较大,所以配置JVM修改内存 docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name elastic elasticsearch:6.8.0 原文地址:https://www.

SpringBoot检索篇Ⅳ --- 整合ElasticSearch

知识储备:  关于ElasticSearch的基本使用我已经在上一篇文章介绍过了(传送门),本篇文章主要讲述的是SpringBoot与ElasticSearch的整合以及简单的使用. 原文地址:https://www.cnblogs.com/wangxiayun/p/10271122.html

springboot整合es客户端操作elasticsearch(二)

在上章节中整合elasticsearch客户端出现版本问题进行了处理,这章来进行springboot整合得操作 环境:elaticsearch6.2.1,springboot 2.1.8 客户端版本采用6.6.1 一 pom.xml依赖引入 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns

Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询

运行环境:JDK 7 或 8,Maven 3.0+技术栈:SpringBoot 1.5+,ElasticSearch 2.3.2 本文提纲一.ES 的使用场景二.运行 springboot-elasticsearch 工程三.springboot-elasticsearch 工程代码详解 一.ES 的使用场景 简单说,ElasticSearch(简称 ES)是搜索引擎,是结构化数据的分布式搜索引擎.在<Elasticsearch 和插件 elasticsearch-head 安装详解>  和