惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Troy Hunt's Blog
T
The Exploit Database - CXSecurity.com
Microsoft Security Blog
Microsoft Security Blog
V
Visual Studio Blog
F
Fortinet All Blogs
博客园_首页
P
Proofpoint News Feed
V
Vulnerabilities – Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
S
Security Affairs
The Register - Security
The Register - Security
S
Security @ Cisco Blogs
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
Schneier on Security
Schneier on Security
WordPress大学
WordPress大学
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
T
Tailwind CSS Blog
Hacker News: Ask HN
Hacker News: Ask HN
W
WeLiveSecurity
D
Docker
L
LangChain Blog
B
Blog RSS Feed
The Last Watchdog
The Last Watchdog
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
N
Netflix TechBlog - Medium
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
The Hacker News
The Hacker News
AWS News Blog
AWS News Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
宝玉的分享
宝玉的分享
I
Intezer
云风的 BLOG
云风的 BLOG
V2EX - 技术
V2EX - 技术
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

李锋镝的博客

LiteLLM 本地代理搭建 Claude-HUD 使用文档 Kratos+ —— Kratos 主题二次开发记录 译文:如何将单体应用拆解为微服务 codebase-memory-mcp 极简完整使用指南 Claude Haiku 4.5、Claude Sonnet 4.6、Claude Opus 4.7 区别以及各自的新特性 SchedulingConfigurer详解 踩坑60+次后,我终于搞懂 Claude Skill 怎么写才会真的触发 Everything Claude Code 详细使用文档 配置Jackson使用字段而不是getter/setter来序列化和反序列化 这个域名注册整整十年了,十年时间,真快啊 Claude Code全维度实战指南:从入门到精通,解锁AI编程新范式 Apollo配置中心中的protalDB的作用是什么 org.apache.ibatis.plugin.Interceptor类详细介绍及使用 岁末 Excel2016右键新建工作表,打开时提示“因为文件格式或文件扩展名无效。请确定文件未损坏,并且文件扩展名与文件的格式匹配。”的解决办法 wordpress增加说说功能 玩博客的人是不是越来越少了? Java 为什么有这么多 “O”? 别再背线程池的七大参数了,现在面试官都这么问 2024年11月1号 农历十月初一 我的第一个WordPress插件:Dylan Custom Plugin上线了 推荐一款比较养眼的Xshell配色方案 hnswlib installation failed 开工啦~ 阳了... MybatisCodeHelperPro激活 @Async注解的坑 新买的笔记本发货啦…… 这个中秋节感觉过的好累啊 IDEA下载源码报:Cannot connect to the Maven process. Try again later. RocketMQ的push消费方式实现详解 看病难~取药难~~ 笑死、腹肌……根本不可能有腹肌的~~ 居家办公了~ C# 11 的这个新特性,我愿称之最强! IntelliJ IDEA 2020.3.x永久白嫖(Windows/Mac) IDEA无限试用方法【2020.3最新亲测有效】 SpringBoot使用注解的方式构建Elasticsearch查询语句,实现多条件的复杂查询 UUID太长怎么办?快来试试NanoId 忽然发现,在校大学生可以免费领一年有道云笔记会员~ 醒醒~补个税了 使用itext和freemarker来根据Html模板生成PDF文件,加水印、印章 来来来,用python画一个冰墩墩儿 SpringBoot整合GraphQL入门教程 办理居住证困难重重啊! 妈呀,昨天晚上睡觉做了一晚上的梦,可累死我了 感觉Typecho很简洁啊…… WordPress的自动更新好烦啊 BeanCopier工具类(性能优化工具类) 内存屏障浅析 居住证可算是申请通过了…… 试了下壁挂炉供暖 关于重阳节 居住证签注... Spring Boot 2.x使用PostgreSQL数据库 十一节后开工头一天,修了个耳机…… 玉楼春·尊前拟把归期说 nginx反向代理配置去除前缀 1931→2021! Navicat Premium数据库账号密码解密 百度的索引量数据现在有点儿太夸张了吧? 哇塞~这个小姐姐实在太惊艳了…… 关于8月29号下午博客故障的一些记录 如何形象的描述反应式编程中的背压(Backpressure)机制? 基于Java8的Either类 海琴烟~~~ JMX监控权限认证配置 IntelliJ IDEA 2019.3.3 永久激活 破解[Windows] SpringBoot整合Elasticsearch游标查询(scroll) GitLab创建新项目,初次提交命令和流程 吐槽下Google浏览器~ 从零搭建Spring Cloud Gateway网关(一) 从零搭建Spring Cloud Gateway网关(二)—— 打印请求响应日志 博客有logo啦 你的答案 数据库事务的一点简单总结 Spring Boot发展史(Spring Boot介绍) 【漫画】戏说外行对程序员的误会有多深 【收藏】从面试官角度观察到的程序员技能瓶颈,同时给出突破瓶颈的建议 Git中.gitignore文件不起作用的解决办法 背影 - 朱自清 jmap命令(jdk1.8) 彻底搞懂mysql日志系统binlog,redolog,undolog 出院了~~~ linux中ftp查看不到文件列表的问题 PHP版本怎么更新啊…… 成语接龙 StarUML4.0破解文件 Java SPI详解 WordPress评论框增加自定义表情 因在公司上不正经网站,我没过试用期… 优化了MYSQL大量写入问题,老板奖励了1000块给我 不慌不忙的坚强(林徽因39段最美文字!) ConcurrentHashMap常用方法源码解析(jdk1.8) 我是如何失去团队掌控的? HBASE填坑日志 关闭apache httpclient4.5 DEBUG日志 使用OpenShift搭建k8s集群 SonarQube Scanner的配置与使用简介
SpringBoot整合Elasticsearch详细步骤以及代码示例(附源码)
李锋镝 · 2021-07-26 · via 李锋镝的博客

准备工作

环境准备

JAVA版本

java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

ES版本

{
  "name": "pYaFJhZ",
  "cluster_name": "my-cluster",
  "cluster_uuid": "oC28y-cNQduGItC7qq5W8w",
  "version": {
    "number": "6.8.2",
    "build_flavor": "oss",
    "build_type": "tar",
    "build_hash": "b506955",
    "build_date": "2019-07-24T15:24:41.545295Z",
    "build_snapshot": false,
    "lucene_version": "7.7.0",
    "minimum_wire_compatibility_version": "5.6.0",
    "minimum_index_compatibility_version": "5.0.0"
  },
  "tagline": "You Know, for Search"
}

SpringBoot版本

2.1.7.RELEASE

开发工具使用的是IDEA

安装ES

Elasticsearch介绍以及安装:ElasticSearch入门-基本概念介绍以及安装

开始

创建SpringBoot项目

  1. 打开IDEA,在菜单中点击
    File > New > Project...
    在弹框中选择Spring Initializr
    图1
    然后Next
  2. 填写项目名等,然后Next
    图2

  3. 选择依赖的jar包(一般我只选Lombok,其他的自己手动加),然后Next
    图3

  4. 最后选择项目所在路径,点击Finish
    图3

搞定收工。至此,一个新的SpringBoot项目就新鲜出炉了。

POM文件

当然,具体依赖的jar包肯定不止第2步选择的那些,其中SpringBoot提供的操作ES的jar包spring-boot-starter-data-elasticsearch当然也是必不可少的。

这里贴出最终的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lifengdi</groupId>
    <artifactId>search</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>search</name>
    <description>elasticsearch</description>

    <properties>
        <java.version>1.8</java.version>
        <testng.version>6.14.2</testng.version>
        <spring-cloud-dependencies.version>Greenwich.RELEASE</spring-cloud-dependencies.version>
        <kibana-logging-spring-boot-starter.version>1.2.4</kibana-logging-spring-boot-starter.version>
        <fastjson.version>1.2.47</fastjson.version>
        <alarm-spring-boot-starter.version>1.0.15-SNAPSHOT</alarm-spring-boot-starter.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud-dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--elasticsearch-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- 日期处理 -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <!--FastJson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml文件

application.yml文件配置如下:

server:
  port: 8080
  servlet:
    context-path: /search
spring:
  application:
    name: search
  data:
    elasticsearch:
      cluster-name: my-cluster
      cluster-nodes: localhost:9300
  jackson:
    default-property-inclusion: non_null

logging:
  file: application.log
  path: .
  level:
    root: info
    com.lifengdi.store.client: DEBUG

index-entity:
  configs:
    - docCode: store
      indexName: store
      type: base
      documentPath: com.lifengdi.document.StoreDocument

spring.data.elasticsearch.cluster-name:集群名称

spring.data.elasticsearch.cluster-nodes:集群节点地址列表,多个节点用英文逗号(,)分隔

创建ES文档和映射

首先创建一个JAVA对象,然后通过注解来声明字段的映射属性。
spring提供的注解有@Document@Id@Field,其中@Document作用在类,@Id@Field作用在成员变量,@Id标记一个字段作为id主键。

package com.lifengdi.document;

import com.lifengdi.document.store.*;
import com.lifengdi.search.annotation.DefinitionQuery;
import com.lifengdi.search.enums.QueryTypeEnum;
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.List;

/**
 * 门店Document
 *
 * @author 李锋镝
 * @date Create at 19:31 2019/8/22
 */
@Document(indexName = "store", type = "base")
@Data
@DefinitionQuery(key = "page", type = QueryTypeEnum.IGNORE)
@DefinitionQuery(key = "size", type = QueryTypeEnum.IGNORE)
@DefinitionQuery(key = "q", type = QueryTypeEnum.FULLTEXT)
public class StoreDocument {

    @Id
    @DefinitionQuery(type = QueryTypeEnum.IN)
    @DefinitionQuery(key = "id", type = QueryTypeEnum.IN)
    @Field(type = FieldType.Keyword)
    private String id;

    /**
     * 基础信息
     */
    @Field(type = FieldType.Object)
    private StoreBaseInfo baseInfo;

    /**
     * 标签
     */
    @Field(type = FieldType.Nested)
    @DefinitionQuery(key = "tagCode", mapped = "tags.key", type = QueryTypeEnum.IN)
    @DefinitionQuery(key = "tagValue", mapped = "tags.value", type = QueryTypeEnum.AND)
    @DefinitionQuery(key = "_tagValue", mapped = "tags.value", type = QueryTypeEnum.IN)
    private List<StoreTags> tags;

}

创建索引

ElasticsearchTemplate提供了四个createIndex()方法来创建索引,可以根据类的信息自动生成,也可以手动指定indexName和Settings

@Override
public <T> boolean createIndex(Class<T> clazz) {
    return createIndexIfNotCreated(clazz);
}

@Override
public boolean createIndex(String indexName) {
    Assert.notNull(indexName, "No index defined for Query");
    return client.admin().indices().create(Requests.createIndexRequest(indexName)).actionGet().isAcknowledged();
}
@Override
public boolean createIndex(String indexName, Object settings) {
    CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName);
    if (settings instanceof String) {
        createIndexRequestBuilder.setSettings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE);
    } else if (settings instanceof Map) {
        createIndexRequestBuilder.setSettings((Map) settings);
    } else if (settings instanceof XContentBuilder) {
        createIndexRequestBuilder.setSettings((XContentBuilder) settings);
    }
    return createIndexRequestBuilder.execute().actionGet().isAcknowledged();
}

@Override
public <T> boolean createIndex(Class<T> clazz, Object settings) {
    return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings);
}

创建映射

ElasticsearchTemplate提供了三个putMapping()方法来创建映射

@Override
public <T> boolean putMapping(Class<T> clazz) {
    if (clazz.isAnnotationPresent(Mapping.class)) {
        String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath();
        if (!StringUtils.isEmpty(mappingPath)) {
            String mappings = readFileFromClasspath(mappingPath);
            if (!StringUtils.isEmpty(mappings)) {
                return putMapping(clazz, mappings);
            }
        } else {
            LOGGER.info("mappingPath in @Mapping has to be defined. Building mappings using @Field");
        }
    }
    ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
    XContentBuilder xContentBuilder = null;
    try {

        ElasticsearchPersistentProperty property = persistentEntity.getRequiredIdProperty();

        xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(),
                property.getFieldName(), persistentEntity.getParentType());
    } catch (Exception e) {
        throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e);
    }
    return putMapping(clazz, xContentBuilder);
}

@Override
public <T> boolean putMapping(Class<T> clazz, Object mapping) {
    return putMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType(),
            mapping);
}

@Override
public boolean putMapping(String indexName, String type, Object mapping) {
    Assert.notNull(indexName, "No index defined for putMapping()");
    Assert.notNull(type, "No type defined for putMapping()");
    PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(indexName).setType(type);
    if (mapping instanceof String) {
        requestBuilder.setSource(String.valueOf(mapping), XContentType.JSON);
    } else if (mapping instanceof Map) {
        requestBuilder.setSource((Map) mapping);
    } else if (mapping instanceof XContentBuilder) {
        requestBuilder.setSource((XContentBuilder) mapping);
    }
    return requestBuilder.execute().actionGet().isAcknowledged();
}

测试代码如下

@Test
public void testCreate() {
    System.out.println(elasticsearchTemplate.createIndex(StoreDocument.class));
    System.out.println(elasticsearchTemplate.putMapping(StoreDocument.class));
}

删除索引

ElasticsearchTemplate提供了2个deleteIndex()方法来删除索引

@Override
public <T> boolean deleteIndex(Class<T> clazz) {
    return deleteIndex(getPersistentEntityFor(clazz).getIndexName());
}

@Override
public boolean deleteIndex(String indexName) {
    Assert.notNull(indexName, "No index defined for delete operation");
    if (indexExists(indexName)) {
        return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged();
    }
    return false;
}

新增&修改文档

在Elasticsearch中文档是不可改变的,不能修改它们。相反,如果想要更新现有的文档,需要重建索引或者进行替换。

所以可以使用和新增同样的接口来对文档进行修改操作。区分的依据就是id。

下面提供新增&修改文档的其中两种方法,一种是通过ElasticsearchTemplate提供的index()方法:

@Override
public String index(IndexQuery query) {
    String documentId = prepareIndex(query).execute().actionGet().getId();
    // We should call this because we are not going through a mapper.
    if (query.getObject() != null) {
        setPersistentEntityId(query.getObject(), documentId);
    }
    return documentId;
}

示例代码如下:

/**
 * 更新索引
 * @param indexName 索引名称
 * @param type 索引类型
 * @param id ID
 * @param jsonDoc JSON格式的文档
 * @param refresh 是否刷新索引
 * @return ID
 */
public String index(String indexName, String type, String id, JsonNode jsonDoc, boolean refresh)
            throws JsonProcessingException {

        log.info("AbstractDocumentIndexService更新索引.indexName:{},type:{},id:{},jsonDoc:{}", indexName, type, id, jsonDoc);
        IndexQuery indexQuery = new IndexQueryBuilder()
                .withIndexName(indexName)
                .withType(type)
                .withId(id)
                .withSource(objectMapper.writeValueAsString(jsonDoc))
                .build();
        try {
            if (elasticsearchTemplate.indexExists(indexName)) {
                String index = elasticsearchTemplate.index(indexQuery);
                if (refresh) {
                    elasticsearchTemplate.refresh(indexName);
                }
                return index;
            }
        } catch (Exception e) {
            log.error("更新索引失败,刷新ES重试", e);
            elasticsearchTemplate.refresh(indexName);
            return elasticsearchTemplate.index(indexQuery);
        }
        throw BaseException.INDEX_NOT_EXISTS_EXCEPTION.build();
    }

另一种则是通过Repository接口。Spring提供的ES的Repository接口为ElasticsearchCrudRepository,所以我们就可以直接定义额新的接口,然后实现ElasticsearchCrudRepository即可:

package com.taoche.docindex.repo;

import com.taoche.document.StoreDocument;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * 门店Repository
 * @author 李锋镝
 * @date Create at 09:30 2019/8/23
 */
public interface StoreRepository extends ElasticsearchRepository<StoreDocument, String> { }

示例代码如下:

@Test
public void testSave() {

    StoreDocument storeDocument = new StoreDocument();
    storeDocument.setId("1");
    StoreBaseInfo baseInfo = new StoreBaseInfo();
    baseInfo.setStoreId("1");
    baseInfo.setCreatedTime(DateTime.now());
    storeDocument.setBaseInfo(baseInfo);

    storeRepository.save(storeDocument);
}

查询

ES的主要功能就是查询,ElasticsearchRepository也提供了基本的查询接口,比如findById()findAll()findAllById()search()等方法;当然也可以使用Spring Data提供的另外一个功能:Spring Data JPA——通过方法名创建查询,当然需要遵循一定的规则,比如你的方法名叫做findByTitle(),那么它就知道你是根据title查询,然后自动帮你完成,这里就不仔细说了。

上边说的基本能满足一般的查询,复杂一点的查询就无能为力了,这就需要用到自定义查询,这里可以查看我的另一篇博客SpringBoot使用注解的方式构建Elasticsearch查询语句,实现多条件的复杂查询,这里边有详细的说明。

另外还有一个比较厉害的功能,Elasticsearch的聚合;聚合主要实现的是对数据的统计、分析。这个暂时没有用到的,所以要看聚合功能的小伙伴们可能要失望了~ 哈哈哈~~~

聚合功能以后有时间会再单独说的~都会有的。

至此,SpringBoot整合Elasticsearch基本结束,有什么不明白的地方请留言~

源码

Git项目地址:search

如果觉得有帮助的话,请帮忙点赞、点星小小的支持一下~

谢谢

除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.lifengdi.com/article/945