尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

CocoIndex 向量索引 10 分钟教程:把 Markdown 文件夹变成可语义搜索的 Postgres 向量库

CocoIndex 向量索引 10 分钟教程:把 Markdown 文件夹变成可语义搜索的 Postgres 向量库 CocoIndex 向量索引 10 分钟教程把 Markdown 文件夹变成可语义搜索的 Postgres 向量库【免费下载链接】cocoindexIncremental engine for long horizon agents Star if you like it!项目地址: https://gitcode.com/GitHub_Trending/co/cocoindex你手里攒了一堆 Markdown 文档想做按语义搜索却不知道从哪建索引。CocoIndex 向量索引就是干这件事的开源引擎你用 Python 声明目标里该长什么样Rust 引擎负责把库和目标持续对齐。文件改了一个它就只重新处理那一个。先给你看终点再倒推过程。 先跑一遍看成果想象你敲完最后一条命令终端给出这个$ cocoindex update main documents: 3 added, 0 removed, 0 updatedadded是这次新入库的文档数removed是源文件删除后引擎顺手清掉的行数updated是内容变动后重算的行数。跑通之后你手里多了一张 Postgres 表doc_embeddings每个文档块一行存着文本、文件名、字符偏移和 embedding 向量embedding 就是文本的向量表示语义越近的文本向量距离越近embedding 列上还挂了一个 pgvector 向量索引直接按余弦相似度查。这张动图展示引擎的核心动作每次运行只重算变化的那部分而不是把整个语料重新洗一遍。️ 装好环境安装 CocoIndex[embeddings]附带本地向量化所需的依赖pip install -U cocoindex[embeddings]起一个带 pgvector 插件的 Postgres。CocoIndex 用它存向量配置文件dev/postgres.yaml就在仓库里docker compose -f dev/postgres.yaml up -d创建你自己的项目目录mkdir cocoindex-quickstart cd cocoindex-quickstart放几份示例 Markdown 进去mkdir markdown_files cd markdown_files curl -L -O https://gitcode.com/GitHub_Trending/co/cocoindex/raw/main/docs/src/content/docs/getting_started/markdown_files.zip unzip markdown_files.zip cd ..markdown_files.zip是仓库自带的三篇示例文档后面会直接跑它们。 读懂核心代码新建main.py按下面四段走读。第一段是数据行每行代表一个文档块chunking把长文档切成小块再逐块向量化from dataclasses import dataclass from typing import Annotated import cocoindex as coco from cocoindex.connectors import localfs, postgres from cocoindex.ops.text import RecursiveSplitter from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder from cocoindex.resources.file import FileLike, PatternFilePathMatcher from cocoindex.resources.id import IdGenerator import numpy.typing import pathlib EMBED_MODEL sentence-transformers/all-MiniLM-L6-v2 _splitter RecursiveSplitter() dataclass class DocEmbedding: id: int filename: str chunk_start: int chunk_end: int text: str embedding: Annotated[numpy.typing.NDArray, EMBED_MODEL]DocEmbedding就是将来表里的一行。embedding字段用Annotated标注了模型名维度由嵌入器自动推断不用手写。第二段是文件级处理函数分块和向量化都发生在里面coco.fn(memoTrue) async def process_file(file: FileLike, table: postgres.TableTarget[DocEmbedding]): text await file.read_text() chunks _splitter.split(text, chunk_size2000, chunk_overlap500, languagemarkdown) id_gen IdGenerator() for chunk in chunks: table.declare_row( rowDocEmbedding( idawait id_gen.next_id(chunk.text), filenamefile.file_path.path.name, chunk_startchunk.start.char_offset, chunk_endchunk.end.char_offset, textchunk.text, embeddingawait SentenceTransformerEmbedder(EMBED_MODEL).embed(chunk.text), ) )RecursiveSplitter按 Markdown 结构把文档切成约 2000 字的块相邻块重叠 500 字跨边界的想法不会被拦腰截断。每个块交给本地模型all-MiniLM-L6-v2生成向量不用 API key不出内网。头部的memoTrue是关键引擎给函数输入和代码算指纹文件没变下次直接跳过。第三段挂目标、接数据源coco.fn async def app_main(sourcedir: pathlib.Path): table await postgres.mount_table_target( DATABASE_URL, table_namedoc_embeddings, table_schemaawait postgres.TableSchema.from_class(DocEmbedding, primary_key[id]), ) table.declare_vector_index(columnembedding) files localfs.walk_dir( sourcedir, recursiveTrue, path_matcherPatternFilePathMatcher(included_patterns[**/*.md]), ) await coco.mount_each(process_file, files.items(), table)mount_table_target按 dataclass 自动建表、接管后续所有 upsert 和清理declare_vector_index给 embedding 列加上 pgvector 向量索引walk_dir递归列出全部.md文件mount_each给每个文件挂一个处理组件文件级互不干扰。最后把一切绑成一个应用DATABASE_URL postgres://cocoindex:cocoindexlocalhost:5432/cocoindex app coco.App( coco.AppConfig(nameTextEmbedding), app_main, sourcedirpathlib.Path(./markdown_files), )coco.App就是 CocoIndex 的运行单元入口函数、输入目录、应用名三样绑好交给 CLI 调度。▶️ 运行并验证数据库地址已经在代码里写死这里只需要告诉 CocoIndex 自己把状态存哪export COCOINDEX_DB./cocoindex.db cocoindex update main第一条命令指定状态库位置默认就是本地一个 SQLite 文件引擎在里面记录每个文件的处理指纹增量更新全靠它。首次运行要下载all-MiniLM-L6-v2模型稍等片刻成功后看到上面那行documents: 3 added...。确认数据真的落库连进 Postgres 看一眼psql postgres://cocoindex:cocoindexlocalhost:5432/cocoindex -c SELECT count(*), vector_dims(embedding) FROM cocoindex.doc_embeddings;它会告诉你表里有多少行、向量维度是多少。仓库自带的examples/text_embedding/main.py里还带一个交互式查询脚本可以跑python main.py what is self-attention?用同一个模型把问题向量化后按相似度返回最相近的块。 接下来看什么想深入原理读 官方文档 的 Core Concepts 和 Programming Guide。仓库根目录的 examples/ 有 20 多个完整示例image_search/ 做以图搜图meeting_notes_graph_neo4j/ 把会议笔记长成知识图谱postgres_source/ 从 Postgres 读源数据。照抄一个目录改两行配置就能变成你自己的索引。现在建个空目录、丢进几份 Markdown跑一遍cocoindex update main你的第一个向量索引就建好了。【免费下载链接】cocoindexIncremental engine for long horizon agents Star if you like it!项目地址: https://gitcode.com/GitHub_Trending/co/cocoindex创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表