什么是索引?
- 定义:索引是 elasticsearch 中用于存储数据的逻辑命名空间。它由多个文档组成,每个文档是一个 json 格式的结构化数据
- 对应关系:在关系数据库中,索引类似于表;而在 elasticsearch 中,索引则相当于数据库的集合或目录。
依赖
选择方案一
使用这个依赖的话必须搭配配置类去使用
<!-- elasticsearch -->
<dependency>
<groupid>org.elasticsearch</groupid>
<artifactid>elasticsearch</artifactid>
<version>7.7.0</version>
</dependency>
<dependency>
<groupid>org.elasticsearch.client</groupid>
<artifactid>elasticsearch-rest-high-level-client</artifactid>
<version>7.7.0</version>
</dependency>选择方案二
使用这个依赖的话配置类可写可不写,因为springboot工程已经帮我们自动的去完成配置了,不需要我们自己写了
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-data-elasticsearch</artifactid>
</dependency>配置
es: host: 111.229.0.43 port: 9200 scheme: http
配置类
package com.macro.mall.demo.config;
import lombok.data;
import org.apache.http.httphost;
import org.elasticsearch.client.restclient;
import org.elasticsearch.client.resthighlevelclient;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.stereotype.component;
@data
@component
public class initesres {
@value("${es.host}")
private string host;
@value("${es.port}")
private int port;
@value("${es.scheme}")
private string scheme;
@bean
public resthighlevelclient resthighlevelclient(){
return new resthighlevelclient(
restclient.builder(new httphost(host,port,scheme))
);
}
}dto
package com.macro.mall.demo.dto;
import io.swagger.annotations.apimodelproperty;
import jakarta.validation.constraints.notempty;
import jakarta.validation.constraints.notnull;
import lombok.data;
/**
* @author:xsp
* @description: es索引传输对象
* @name:esindexdto
* @date:2024/10/16 15:30
*/
@data
public class esindexdto {
/**
* 索引名称
*/
@notempty(message = "索引名称不能为空")
@apimodelproperty(value = "索引名称", required = true, example = "。。。。")
private string indexname;
/**
* 索引映射
*/
@apimodelproperty(value = "索引映射", required = true, example = "。。。。")
private string indexmappings;
/**
* 索引配置
*/
@apimodelproperty(value = "索引配置", required = true, example = "。。。。")
private string indexsettings;
}controller
package com.macro.mall.demo.controller;
import com.macro.mall.common.api.commonresult;
import com.macro.mall.demo.dto.esindexdto;
import com.macro.mall.demo.service.esindexservice;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import jakarta.validation.constraints.notempty;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.validation.annotation.validated;
import org.springframework.web.bind.annotation.*;
import java.util.map;
/**
* @author:xsp
* @description: es索引管理
* @name:escontroller
* @date:2024/10/15 20:38
*/
@restcontroller
@requestmapping("/index")
@validated
@api(tags = "es索引管理")
public class esindexcontroller {
@autowired
private esindexservice esindexservice;
/**
* 创建索引的接口
* @param esindexdto 索引信息
* @return
*/
@apioperation(value = "创建索引")
@postmapping("/create")
public commonresult createindex(@validated @requestbody esindexdto esindexdto) {
esindexservice.createindex(esindexdto);
return commonresult.successmessage("索引创建成功"); // 调用服务方法创建索引
}
/**
* 删除索引的接口
* @param indexname 索引名称
* @return
*/
@apioperation(value = "删除索引")
@deletemapping("/delete")
public commonresult deleteindex(@requestparam @notempty(message = "索引名称不能为空") string indexname) {
esindexservice.deleteindex(indexname); // 调用服务方法删除索引
return commonresult.successmessage("索引删除成功");
}
/**
* 获取索引的接口
* @param indexname 索引名称
* @return
*/
@apioperation(value = "获取索引映射")
@getmapping("/get")
public commonresult<map<string, object>> getindex(@requestparam @notempty(message = "索引名称不能为空") string indexname) {
map<string, object> indexmappings = esindexservice.getindex(indexname);
return commonresult.success(indexmappings); // 调用服务方法获取索引
}
/**
* 根据索引名称修改索引配置
* @param esindexdto 索引信息
* @return
*/
@apioperation(value = "修改索引配置")
@putmapping("/update")
public commonresult updateindex(@validated @requestbody esindexdto esindexdto) {
esindexservice.updateindex(esindexdto);
return commonresult.successmessage("索引更新成功"); // 调用服务方法更新索引
}
/**
* 判断索引是否存在
* @param indexname 索引名称
* @return
*/
@apioperation(value = "判断索引是否存在")
@getmapping("/exists")
public commonresult exists(@requestparam @notempty(message = "索引名称不能为空") string indexname) {
boolean exists =esindexservice.exists(indexname);
return commonresult.success(exists);
}
}serveice
package com.macro.mall.demo.service;
import com.macro.mall.demo.dto.esdocdto;
import com.macro.mall.demo.dto.esindexdto;
import java.util.list;
import java.util.map;
/**
* @author:xsp
* @description:
* @name:esservice
* @date:2024/10/15 20:39
*/
public interface esdocservice {
/**
* 批量添加
* @param esdocdto 文档信息
*/
void batchadd(esdocdto esdocdto);
/**
* 批量删除
* @param indexname 索引名称
* @param ids 多个id
*/
void batchdelete(string indexname, list<string> ids);
}impl
package com.macro.mall.demo.service.impl;
import com.macro.mall.demo.dto.esdocdto;
import com.macro.mall.demo.dto.esindexdto;
import com.macro.mall.demo.service.esindexservice;
import lombok.extern.log4j.log4j2;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.lang3.stringutils;
import org.elasticsearch.action.admin.indices.create.createindexrequest;
import org.elasticsearch.action.admin.indices.delete.deleteindexrequest;
import org.elasticsearch.action.admin.indices.settings.put.updatesettingsrequest;
import org.elasticsearch.client.requestoptions;
import org.elasticsearch.client.resthighlevelclient;
import org.elasticsearch.client.indices.getindexrequest;
import org.elasticsearch.client.indices.getindexresponse;
import org.elasticsearch.common.xcontent.xcontenttype;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
import java.util.map;
/**
* @author:xsp
* @description:
* @name:esserviceimpl
* @date:2024/10/15 20:39
*/
@service
@slf4j
public class esindexserviceimpl implements esindexservice {
@autowired
private resthighlevelclient resthighlevelclient;
/**
* 创建索引
*
* @param esindexdto 索引信息
*/
@override
public void createindex(esindexdto esindexdto) {
// 检查索引是否已存在
if (exists(esindexdto.getindexname())) {
throw new runtimeexception("索引已经存在: " + esindexdto.getindexname());
}
// 创建索引请求
createindexrequest request = new createindexrequest(esindexdto.getindexname());
// 设置索引配置
if (stringutils.isnotblank(esindexdto.getindexmappings())) {
request.settings(esindexdto.getindexmappings(), xcontenttype.json);
}
// 执行创建索引操作
try {
resthighlevelclient.indices().create(request, requestoptions.default);
log.info("索引创建成功: {}", esindexdto.getindexname());
} catch (exception e) {
log.error("创建索引失败, 错误信息: {}", e.getmessage());
throw new runtimeexception("创建索引失败: " + esindexdto.getindexname(), e);
}
}
/**
* 删除索引
*
* @param indexname 索引名称
*/
@override
public void deleteindex(string indexname) {
// 检查索引是否存在
if (!exists(indexname)) {
throw new runtimeexception("索引不存在: " + indexname);
}
// 创建删除索引请求
deleteindexrequest request = new deleteindexrequest(indexname);
// 执行删除索引操作
try {
resthighlevelclient.indices().delete(request, requestoptions.default);
log.info("索引删除成功: {}", indexname);
} catch (exception e) {
log.error("删除索引失败, 错误信息: {}", e.getmessage());
throw new runtimeexception("删除索引失败: " + indexname, e);
}
}
/**
* 获取索引映射
*
* @param indexname 索引名称
* @return 索引映射信息
*/
@override
public map<string, object> getindex(string indexname) {
// 检查索引是否存在
if (!exists(indexname)) {
throw new runtimeexception("索引不存在: " + indexname);
}
// 创建获取索引请求
getindexrequest request = new getindexrequest(indexname);
// 执行获取索引映射操作
try {
getindexresponse response = resthighlevelclient.indices().get(request, requestoptions.default);
log.info("获取索引映射成功: {}", indexname);
return response.getmappings().get(indexname).sourceasmap(); // 返回索引映射
} catch (exception e) {
log.error("获取索引映射失败, 错误信息: {}", e.getmessage());
throw new runtimeexception("获取索引映射失败: " + indexname, e);
}
}
/**
* 更新索引配置
*
* @param esindexdto 索引信息
*/
@override
public void updateindex(esindexdto esindexdto) {
// 检查索引是否存在
if (!exists(esindexdto.getindexname())) {
throw new runtimeexception("索引不存在: " + esindexdto.getindexname());
}
// 创建更新索引设置请求
updatesettingsrequest request = new updatesettingsrequest(esindexdto.getindexname());
// 更新索引映射
if (stringutils.isnotblank(esindexdto.getindexmappings())) {
request.settings(esindexdto.getindexmappings(), xcontenttype.json);
}
// 执行更新索引设置操作
try {
boolean acknowledged = resthighlevelclient.indices().putsettings(request, requestoptions.default).isacknowledged();
if (acknowledged) {
log.info("索引设置更新成功: {}", esindexdto.getindexname());
} else {
log.warn("索引设置更新未被确认: {}", esindexdto.getindexname());
}
} catch (exception e) {
log.error("更新索引设置失败, 错误信息: {}", e.getmessage());
throw new runtimeexception("更新索引设置失败: " + esindexdto.getindexname(), e);
}
}
/**
* 判断索引是否存在
*
* @param indexname 索引名称
* @return 索引是否存在
*/
@override
public boolean exists(string indexname) {
// 创建获取索引请求
getindexrequest request = new getindexrequest(indexname);
try {
// 执行获取索引操作并返回索引是否存在
boolean exists = resthighlevelclient.indices().exists(request, requestoptions.default);
log.info("判断索引是否存在: {}, 结果: {}", indexname, exists);
return exists;
} catch (exception e) {
log.error("判断索引是否存在失败, 错误信息: {}", e.getmessage());
return false; // 返回判断失败
}
}
}统一结果集
package com.macro.mall.common.api;
import cn.hutool.json.jsonutil;
/**
* 通用返回对象
* created by 9a8204a7-f77d-4ab8-ae70-b4721fef2f95 on 2019/4/19.
*/
public class commonresult<t> {
private long code;
private string message;
private t data;
protected commonresult() {
}
protected commonresult(long code, string message, t data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回信息
* @param message 提示信息
*/
public static <t> commonresult<t> successmessage(string message) {
return new commonresult<t>(resultcode.success.getcode(), message, null);
}
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <t> commonresult<t> success(t data) {
return new commonresult<t>(resultcode.success.getcode(), resultcode.success.getmessage(), data);
}
/**
* 成功返回结果
*
* @param data 获取的数据
* @param message 提示信息
*/
public static <t> commonresult<t> success(t data, string message) {
return new commonresult<t>(resultcode.success.getcode(), message, data);
}
/**
* 失败返回结果
* @param errorcode 错误码
*/
public static <t> commonresult<t> failed(ierrorcode errorcode) {
return new commonresult<t>(errorcode.getcode(), errorcode.getmessage(), null);
}
/**
* 失败返回结果
* @param errorcode 错误码
* @param message 错误信息
*/
public static <t> commonresult<t> failed(ierrorcode errorcode,string message) {
return new commonresult<t>(errorcode.getcode(), message, null);
}
/**
* 失败返回结果
* @param message 提示信息
*/
public static <t> commonresult<t> failed(string message) {
return new commonresult<t>(resultcode.failed.getcode(), message, null);
}
/**
* 失败返回结果
*/
public static <t> commonresult<t> failed() {
return failed(resultcode.failed);
}
/**
* 参数验证失败返回结果
*/
public static <t> commonresult<t> validatefailed() {
return failed(resultcode.validate_failed);
}
/**
* 参数验证失败返回结果
* @param message 提示信息
*/
public static <t> commonresult<t> validatefailed(string message) {
return new commonresult<t>(resultcode.validate_failed.getcode(), message, null);
}
/**
* 未登录返回结果
*/
public static <t> commonresult<t> unauthorized(t data) {
return new commonresult<t>(resultcode.unauthorized.getcode(), resultcode.unauthorized.getmessage(), data);
}
/**
* 未授权返回结果
*/
public static <t> commonresult<t> forbidden(t data) {
return new commonresult<t>(resultcode.forbidden.getcode(), resultcode.forbidden.getmessage(), data);
}
public long getcode() {
return code;
}
public void setcode(long code) {
this.code = code;
}
public string getmessage() {
return message;
}
public void setmessage(string message) {
this.message = message;
}
public t getdata() {
return data;
}
public void setdata(t data) {
this.data = data;
}
@override
public string tostring() {
return jsonutil.tojsonstr(this);
}
}这里我用的是这个统一结果集,结合自己实际情况去使用相对应的统一结果集
spring原生效验异常
@responsebody
@exceptionhandler(value = apiexception.class)
public commonresult handle(apiexception e) {
if (e.geterrorcode() != null) {
return commonresult.failed(e.geterrorcode());
}
return commonresult.failed(e.getmessage());
}
@responsebody
@exceptionhandler(value = methodargumentnotvalidexception.class)
public commonresult handlevalidexception(methodargumentnotvalidexception e) {
bindingresult bindingresult = e.getbindingresult();
string message = null;
if (bindingresult.haserrors()) {
fielderror fielderror = bindingresult.getfielderror();
if (fielderror != null) {
message = fielderror.getfield()+fielderror.getdefaultmessage();
}
}
return commonresult.validatefailed(message);
}
@responsebody
@exceptionhandler(value = bindexception.class)
public commonresult handlevalidexception(bindexception e) {
bindingresult bindingresult = e.getbindingresult();
string message = null;
if (bindingresult.haserrors()) {
fielderror fielderror = bindingresult.getfielderror();
if (fielderror != null) {
message = fielderror.getfield()+fielderror.getdefaultmessage();
}
}
return commonresult.validatefailed(message);
}
/**
* 最大异常
* @param e
* @return
*/
@responsebody
@exceptionhandler(value = exception.class)
public commonresult handle(exception e) {
e.printstacktrace();
return commonresult.validatefailed(e.getmessage());
}这里我是用的这几个写的异常捕获器,结合自己实际情况去使用相对应的异常捕获
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论