Easy-Es对Elasticsearch7.14向量检索,原生脚本写法

java 复制代码
import com.xinren.cdc.XrDataCdcApplication;
import com.xinren.cdc.dao.domian.es.DenseVectorData;
import com.xinren.cdc.dao.index.DenseVectorIndex;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.dromara.easyes.core.conditions.update.LambdaEsUpdateWrapper;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScriptScoreQueryBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@SpringBootTest(classes = XrDataCdcApplication.class)
class XrDataCdcApplicationTests {

    @Resource
    private DenseVectorIndex denseVectorIndex;

    @Test
    void createIndex() {
        denseVectorIndex.createIndex();
    }
    @Test
    void addIndex(){
        DenseVectorData data = new DenseVectorData();
        data.setId("1");
        data.setText("大家好,才是真的好");
        double[] doubles = new double[]{0.1,0.2,0.3,0.4,0.5};
        data.setVectors(doubles);
        denseVectorIndex.insert(data);
    }
    @Test
    void queryIndex(){
        double[] doubles = new double[]{0.1,0.2,0.3,0.4,0.5};
        Map<String, Object> params = Collections.singletonMap("query_vector", doubles);
        LambdaEsQueryWrapper<DenseVectorData> wrapper = new LambdaEsQueryWrapper<>();
        // 余弦相似
        Script scriptYx = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG,
                "cosineSimilarity(params.query_vector, 'vectors') + 1.0", params);
        // 点积距离
        Script scriptDj = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG,
                "dotProduct(params.query_vector, doc['vectors']) + 1",params);

        // 曼哈顿距离:l1norm
        Script scriptL1norm = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG,
                "1 / (1 + l1norm(params.query_vector, doc['vectors']))",params);

        // 欧几里得距离:l2norm
        Script scriptL2norm = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG,
                "1 / (1 + l2norm(params.query_vector, doc['vectors']))",params);

        // 曼哈顿距离的Painless自定义脚本(需要手动编写计算逻辑)
        String scriptSource = "double sum = 0;"
                + "for (int i = 0; i < params.query_vector.length; i++) {"
                + "  sum += Math.abs((doc['vectors'].vectorValue)[i] - params.query_vector[i]);"
                + "}"
                + "return sum;";
        // 创建Painless脚本
        Script scriptMhd = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, scriptSource, params);

        wrapper.setSearchSourceBuilder(new SearchSourceBuilder().query(new ScriptScoreQueryBuilder(new MatchAllQueryBuilder(),scriptMhd)));
        List<DenseVectorData> denseVectorData = denseVectorIndex.selectList(wrapper);

        System.out.println(denseVectorData);
    }

    @Test
    void delIndex(){
        LambdaEsUpdateWrapper<DenseVectorData> wrapper = new LambdaEsUpdateWrapper<>();
        wrapper.eq(DenseVectorData::getId,"1");
        denseVectorIndex.delete(wrapper);
    }

}

Elasticsearch7.14安装插件后,创建查询索引

javascript 复制代码
PUT /my_index
{
  "mappings": {
    "properties": {
      "my_vector_field": {
        "type": "dense_vector",
        "dims": 3,      // 向量维度
        "similarity": "l2_norm" // 或 "cosine"
      }
    }
  }
}

POST /my_index/_doc
{
  "my_vector_field": [0.1, 0.2, 0.3], // 3维的向量数据
  "content": "这是文档的其他文本信息..."
}

GET /my_index/_search
{
  "query": {
    "elastiknn_nearest_neighbors": {
      "field": "my_vector_field",
      "model": "l2", // 或 "cosine"
      "vector": [0.1, 0.2, 0.3],
      "k": 5          // 返回最相似的 top-k 结果
    }
  }
}
相关推荐
Flynt10 小时前
Java4Shell 实测:EPYC 一跑就中招,关掉 Base64 硬件加速,1KB 解码慢 14 倍
java·安全·性能优化
Resean022310 小时前
Spring 源码分析(七)AOP 原理(上):代理的创建
java·后端·spring
Tangq一定可以的10 小时前
Spring AI Advisor 详解 - 给大模型调用加上“切面“,日志/过滤/记忆一键搞定
java·后端·spring
wuyk55510 小时前
Spider-第16讲-线程池与竞态问题
大数据·爬虫·python·elasticsearch·搜索引擎
小巫编程室11 小时前
我造了一个 Java 能力包:让 AI 直接调用你的业务代码
java·前端·后端
深入云栈11 小时前
Netty 4.2.x 源码深度解析 (二十四):池化内存分配 —— PoolArena、PoolChunk 与 PoolSubpage
java·后端·架构
惜.己12 小时前
Java结合idea简单使用Playwright
java·开发语言·自动化
Vex2une13 小时前
JDK 8 下载安装与环境变量配置完整指南(Windows新手图文教程)
java·windows·环境配置·环境变量·jdk8·jdk下载安装·java入门教程
文丑颜不良啊14 小时前
LeetCode3281~3300题目解析
java·leetcode
nice_lcj52015 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型