es的集成与使用

es集成到java项目中

项目源码:https://gitee.com/lilinchun/es-project.git
首先有一个初始化的项目
第一步导入项目包

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons</artifactId>
			<version>2.7.0</version>
		</dependency>

		<!-- 阿里巴巴的druid数据源 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.23</version>
		</dependency>
		<!-- Mybatis-Plus 依赖配置 -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.3.2</version>
			<exclusions>
				<exclusion>
					<artifactId>mybatis-plus-extension</artifactId>
					<groupId>com.baomidou</groupId>
				</exclusion>
			</exclusions>
		</dependency>

		<!--   mybatis-plus代码生成器     -->
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.3.1</version>
		</dependency>
		<!--es-->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-elasticsearch</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>

	</dependencies>

yml配置

server:
  port: 8080
spring:
  application:
    name: es-service #\u9879\u76EE\u540D\u79F0
  datasource:
    driver-class-name:  com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://81.68.207.210:3306/blog?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456


  elasticsearch:
    rest:
      ## ES 的地址
      uris: 81.68.207.210:9200
    index:
      ## 索引前缀
      prefix: endpoint-authmanager
      length: 7

es的仓库配置

package com.llc.dao;


import com.llc.es.BlogEs;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BlogRepository extends ElasticsearchRepository<BlogEs, String> {

}

package com.llc.es;

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;

import java.util.Date;

/**
 * @author lilinchun
 * @date 2022/9/16 0016 17:22
 */
@Data
//llc_blog_new这个是创建的索引
@Document(indexName ="llc_blog_new" )
public class BlogEs {

    @Id
    @Field(type = FieldType.Long)
    private Long blogId;

    //标题
    @Field(type = FieldType.Text)
    private String title;

    @Field(type = FieldType.Long)
    private Long uid;
    //内容
    @Field(type = FieldType.Text)
    private String content;

    //创建时间
    @Field(type = FieldType.Date)
    private Date createTime;

    //首图
    @Field(type = FieldType.Text)
    private String firstPicture;

    //完成状态
    @Field(type = FieldType.Text)
    private String flag;

    //点赞数
    @Field(type = FieldType.Integer)
    private Integer thumbs;

    //发布状态
    @Field(type = FieldType.Integer)
    private Integer published;

    //推荐状态
    @Field(type = FieldType.Integer)
    private Integer recommend;

    //版权状态
    @Field(type = FieldType.Text)
    private String shareStatement;
    //更新时间
    @Field(type = FieldType.Date)
    private Date updateTime;

    //浏览次数
    @Field(type = FieldType.Integer)
    private Integer views;

    @Field(type = FieldType.Long)
    private Long typeId;

    @Field(type = FieldType.Text)
    private String description;

    //赞赏状态
    @Field(type = FieldType.Integer)
    private Integer appreciation;

    //评论状态
    @Field(type = FieldType.Integer)
    private Integer commentabled;


}

测试

package com.llc.controller;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.llc.dao.BlogRepository;
import com.llc.entity.Blog;
import com.llc.es.BlogEs;
import com.llc.service.BlogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;

/**
 * (Blog)表控制层
 *
 * @author makejava
 * @since 2022-09-16 11:37:07
 */
@CrossOrigin
@RestController
@RequestMapping("blog")
public class BlogController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private BlogService blogService;

    @Resource
    private BlogRepository blogRepository;


    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param blog 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<Blog> page, Blog blog) {
        return success(this.blogService.page(page, new QueryWrapper<>(blog)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.blogService.getOne(new LambdaQueryWrapper<Blog>().eq(Blog::getBlogId,id)));
    }


    /**
     * 新增数据
     *
     * @param blog 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody Blog blog) {
        return success(this.blogService.save(blog));
    }

    /**
     * 修改数据
     *
     * @param blog 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody Blog blog) {
        return success(this.blogService.updateById(blog));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return success(this.blogService.removeByIds(idList));
    }


    @GetMapping("get")
    public Blog getTitle(@RequestParam("blogId") String blogId) {
        Blog vo=new Blog();
        Optional<BlogEs> es = blogRepository.findById(blogId);
        System.out.println("es中的数据---------"+es);
        if (es.isPresent()) {
            BlogEs blogEs = es.get();
            BeanUtils.copyProperties(blogEs,vo);
        }
        return vo;
    }
}


测试结果
在这里插入图片描述
这里需要注意导入的es包的版本不想同时配置是有一些差异的
我这里使用的版本
这使用的es版本:elasticsearch:6.8.13
kibana版本:kibana:6.8.13
canal版本:canal1.1.4

es中使用ElasticsearchRestTemplate进行查询

  • 导包
   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>2.7.10</version>
        </dependency>
  • 示例
 	@Resource
    private ElasticsearchRestTemplate template;
    
   @Override
    public List<EsCompany> findAuthedCompany(String companyName) {
        restMemberClient.recordSearchHeat(companyName);
        BoolQueryBuilder queryBuilder = boolQuery().must(matchQuery("companyName", companyName))
                // 已认证
                .must(termQuery("authStatus", "1"));
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                // NativeSearchQuery 默认会分页(page 0,size 10)这里设置我关闭分页
                .withTrackScores(true)
                .build();
        SearchHits<EsCompany> hits = template.search(nativeSearchQuery, EsCompany.class);
        return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
    }


es的需求示例

  • 一个输入框同时查询手机号、姓名、企业名称
 // ES搜索
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.termsQuery("cardId", friendIds))
                .must(QueryBuilders.boolQuery()
                        .should(QueryBuilders.multiMatchQuery(keyword, "realName", "companyName"))
                        .should(QueryBuilders.wildcardQuery("mobile", "*" + keyword + "*"))
                );

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                // 查询条件
                .withQuery(queryBuilder)
                // 分页
                .withPageable(PageRequest.of(Math.max(from - 1, 0), size));
        SearchHits<EsMemberCard> hits = esTemplate.search(nativeSearchQueryBuilder.build(), EsMemberCard.class);
        List<CardHolderSearchListVO> cards = hits.stream()
                .map(hit -> BeanUtil.copy(hit.getContent(), CardHolderSearchListVO.class))
                .collect(Collectors.toList());
        return new PageVO<>(query.getCurrent(), query.getSize(), cards.size(), cards);
  • should :类似sql中表示or
  • wildcardQuery : 类似sql中的like
  • multiMatchQuery:一个词匹配多个参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱上编程2705

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值