如何用faiss强化基于mysql的文本检索
mysql支持基于like的关键字匹配,具备强大的文本检索功能。
然而,当检索问题或关键词与存储的文本差异较大时,like类字符匹配就不能有效发挥作用。
比如,“查询校园绿化方面的规定”,然而数据库中可能仅有“校园花卉种植管理规范”等文档。
虽然绿植和花卉语义一致,但在这种场景下like关键词匹配可能不好发挥作用。
这里尝试基于faiss,采用向量检索的方式,强化mysql的文本检索能力。
1 faiss介绍
1.1 faiss介绍
faiss是Facebook研究院开发的一种高效的相似搜索和聚类库,能够快速处理大规模数据,支持在高维空间进行相似性搜索。
faiss建立vector库过程,即把候选向量集封装成一个index数据库,不需要开发即可实现topk的相似检索过程。
1.2 faiss安装
为简化分析,这里采用conda方式安装,假设conda环境已经创建。
conda install -c pytorch faiss-cpu
pip install faiss-cpu==1.7.2
pip install faiss仅安装一个faiss-cpu的壳子。
如果要正常运行,还需要安装faiss-cpu实体模块,这里采用conda安装。
2 向量检索示例
2.1 测试数据
这里新闻数据库中title字段表示的内容,示例如下所示。
candidates = ['领益智造:打造AI终端硬件制造平台','领益智造在智能手机与人形机器人领域的创新','领益智造积极布局通信和汽车业务','领益智造的投资前景与风险提示','领益智造:打造AI终端硬件制造平台','领益智造在智能手机与人形机器人领域的创新','领益智造积极布局通信和汽车业务','领益智造的投资前景与风险提示','贝斯特:精密机加工领域的隐形冠军','贝斯特:直线滚动功能部件打开新成长空间','贝斯特:精密机加工领域的隐形冠军','光大同创把握折叠屏手机市场机遇,推动新材料创新应用','科技2025展望:AI算力需求与服务器创新引领市场','智能手机市场2025年展望:AI驱动换机周期,创新升级用户体验','AR/VR与汽车电子:AI眼镜与智能化趋势引领未来','公用行业发电量及建议关注板块','全国能源工作会议关注特高压与核电投资','特高压建设提速,柔直项目渗透率上升','核电发展空间有望打开,多重催化助力成长','新能源车与储能行业12月展望:政策助力,电车储能高歌猛进','谷歌Willow量子芯片重大突破,量子计算商业化加速在即','博通ASIC业务超预期,配套网络通信设备迎来新机遇','一汽吉林产品研发未跟上市场节奏,陷入经营困境',
]
2.2 faiss检索
from langchain.agents.agent_toolkits import create_retriever_tool
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_ollama import OllamaEmbeddingsembeddings = OllamaEmbeddings(model="bge-m3")vector_db = FAISS.from_texts(candidates, embeddings)
retriever = vector_db.as_retriever(search_kwargs={"k": 3})
print(retriever.invoke("AI算力需求"))
faiss检索输出如下
[Document(id='8d90e6b6-7e81-4a2b-910f-384dfc4c7c98', metadata={}, page_content='科技2025展望:AI算力需求与服务器创新引领市场'), Document(id='ce8905ae-95c8-43af-b7c7-5bcdcc96809a', metadata={}, page_content='领益智造:打造AI终端硬件制造平台'), Document(id='3b19ded6-578f-40f3-8be2-6fc7dd8cb049', metadata={}, page_content='领益智造:打造AI终端硬件制造平台')]
3 mysql + faiss
由于语义搜索方面的优势,这里尝试用向量检索,替代like关键词检索,确定待检索文档,然后再营业sql检索。
3.1 构建向量库
假设我们想为news表的title字段构建faiss向量库。
运行如下sql,收集数据库中所有tag为news的新闻title。
select title from news where tag=“news”;
将所有收集的title存储为candidates,id则用candidates下标表示,范围从0到len(candidates)-1。
运行如下代码狗讲向量库,减速入口为vector_store。
from langchain.agents.agent_toolkits import create_retriever_tool
from langchain_community.vectorstores import FAISS
from langchain_community.docstore.in_memory import InMemoryDocstore
from langchain_openai import OpenAIEmbeddings
from langchain_ollama import OllamaEmbeddings
from langchain_core.documents import Documentembeddings = OllamaEmbeddings(model="bge-m3")
index = faiss.IndexFlatL2(len(embeddings.embed_query("hello world")))vector_store = FAISS(embedding_function=embeddings,index=index,docstore= InMemoryDocstore(),index_to_docstore_id={}
)documents = []
ids = []for i, content in enumerate(candidates):documents.append(Document(page_content=content, metadata={"source": "title"}))ids.append(str(i))vector_store.add_documents(documents=documents, ids=ids)
3.2 向量库检索
需要注意的是,document的id对应的就是title在原始candidates中的位置。
根据id即可对应到原始candidates中title的位置下标。
针对三种不同的场景,这里尝试三种检索方式:过滤检索、score检索、retriefver检索。
1)过滤检索
query = "特高压建设"results = vector_store.similarity_search(query=query,k=1,filter={"source": "title"})
for doc in results:print(f"* id={doc.id} {doc.page_content} [{doc.metadata}]")
2)score检索
results = vector_store.similarity_search_with_score(query=query,k=1)
for doc, score in results:print(f"* [SIM={score:3f}] id={doc.id} {doc.page_content} [{doc.metadata}]")
3)retriever检索
retriever = vector_store.as_retriever(search_type="mmr",search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
)
retriever.invoke(query)
3.3 搜索数据库
构建如下select检索sql,这里id_candidates即为向量检索获得到的文档id列表。
select title, content from news where id in choosen_candidates
附录
import faiss报错
ModuleNotFoundError: No module named 'faiss'
pip install faiss-cpu==1.7.2后依然报错
conda install -c pytorch faiss-cpu后问题解决
reference
---
faiss
https://github.com/facebookresearch/faiss
基于langgraph agent的SQL DB知识库系统
https://blog.csdn.net/liliang199/article/details/153317678
向量数据库-Faiss详解
https://zhuanlan.zhihu.com/p/671776778
查询向量存储
https://python.langchain.ac.cn/docs/integrations/vectorstores/faiss/
langchain_community.vectorstores.faiss.FAISS
https://api.python.langchain.com/en/latest/vectorstores/langchain_community.vectorstores.faiss.FAISS.html
向量数据库-Faiss详解
https://zhuanlan.zhihu.com/p/671776778
