快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索

这篇具有很好参考价值的文章主要介绍了快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Gemini 是 Google DeepMind 开发的多模态大语言模型家族,作为 LaMDA 和 PaLM 2 的后继者。由 Gemini Ultra、Gemini Pro 和 Gemini Nano 组成,于 2023 年 12 月 6 日发布,定位为 OpenAI 的竞争者 GPT-4。

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

本教程演示如何使用 Gemini API 创建嵌入并将其存储在 Elasticsearch 中。 Elasticsearch 将使我们能够执行向量搜索 (Knn) 来查找相似的文档。

准备

Elasticsearch 及 Kibana

如果你还没有安装好自己的 Elasticsearch 及 Kibana 的话,请参阅如下的文章来进行安装:

  • 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch

  • Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 Kibana

在安装的时候,请参照 Elastic Stack 8.x 的文章来进行安装。

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

Gemini 开发者 key

你可以参考文章 来申请一个免费的 key 供下面的开发。你也可以直接去地址进行申请。

设置环境变量

我们在 termnial 中打入如下的命令来设置环境变量:

export ES_USER=elastic
export ES_PASSWORD=-M3aD_m3MHCZNYyJi_V2
export GOOGLE_API_KEY=YourGoogleAPIkey

拷贝 Elasticsearch 证书

我们把 Elasticsearch 的证书拷贝到当前的目录下:

$ pwd
/Users/liuxg/python/elser
$ cp ~/elastic/elasticsearch-8.12.0/config/certs/http_ca.crt .

安装 Python 依赖包

pip3 install -q -U google-generativeai elasticsearch

应用设计

我们在当前的工作目录下打入命令:

jupyter notebook

导入包及环境变量

import google.generativeai as genai
import google.ai.generativelanguage as glm
from elasticsearch import Elasticsearch, helpers
from dotenv import load_dotenv
import os

load_dotenv()

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
ES_USER = os.getenv("ES_USER")
ES_PASSWORD = os.getenv("ES_PASSWORD")
elastic_index_name='gemini-demo'

 连接到 Elasticsearch

url = f"https://{ES_USER}:{ES_PASSWORD}@192.168.0.3:9200"

es = Elasticsearch(
        hosts=[url], 
        ca_certs = "./http_ca.crt", 
        verify_certs = True
)
print(es.info())

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

上面显示我们的 es 连接是成功的。

删除索引

if(es.indices.exists(index=elastic_index_name)):
    print("The index has already existed, going to remove it")
    es.options(ignore_status=404).indices.delete(index=elastic_index_name)

使用 Elasticsearch 索引文档

生成一个 title 为 “Beijing” 文档:

genai.configure(api_key=GOOGLE_API_KEY)

title = "Beijing"
sample_text = ("Beijing is the capital of China and the center of Chinese politics, culture, and economy. This city has a long history with many ancient buildings and cultural heritage. Beijing is renowned as a cultural city in China, boasting numerous museums, art galleries, and historical landmarks. Additionally, as a modern metropolis, Beijing is a thriving business center with modern architecture and advanced transportation systems. It serves as the seat of the Chinese government, where significant decisions and events often take place. Overall, Beijing holds a crucial position in China, serving as both a preserver of traditional culture and a representative of modern development.")

model = 'models/embedding-001'
embedding = genai.embed_content(model=model,
                                content=sample_text,
                                task_type="retrieval_document",
                                title=title)

doc = {
    'text' : sample_text,
    'text_embedding' : embedding['embedding'] 
}

resp = es.index(index=elastic_index_name, document=doc)

print(resp)

生成一个 title 为 “Shanghai” 的文档:

title = "Shanghai"
sample_text = ("Shanghai is one of China's largest cities and a significant hub for economy, finance, and trade. This modern city is located in the eastern part of China and serves as an international metropolis. The bustling streets, skyscrapers, and modern architecture in Shanghai showcase the city's prosperity and development. As one of China's economic engines, Shanghai is home to the headquarters of many international companies and various financial institutions. It is also a crucial trading port, connecting with destinations worldwide. Additionally, Shanghai boasts a rich cultural scene, including art galleries, theaters, and historical landmarks. In summary, Shanghai is a vibrant, modern city with international influence.")

model = 'models/embedding-001'
embedding = genai.embed_content(model=model,
                                content=sample_text,
                                task_type="retrieval_document",
                                title=title)

doc = {
    'text' : sample_text,
    'text_embedding' : embedding['embedding'] 
}

resp = es.index(index=elastic_index_name, document=doc)

print(resp)

我们可以在 Kibana 中进行查看:

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

使用 Elasticsearch 来搜索文档

def search(question):
    print("\n\nQuestion: ", question)
    embedding = genai.embed_content(model=model,
                                    content=question,
                                    task_type="retrieval_query")

    resp = es.search(
    index = elastic_index_name,
    knn={
        "field": "text_embedding",
        "query_vector":  embedding['embedding'],
        "k": 10,
        "num_candidates": 100
        }
    )

    for result in resp['hits']['hits']:
        pretty_output = (f"\n\nID: {result['_id']}\n\nText: {result['_source']['text']}")
        print(pretty_output)
search("How do you describe Beijing?")

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

search("What is Shanghai like?")

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

从上面的输出中,我们可以看出来,当搜索的句子和文章更为接近时,相关的文档就会排在第一的位置。紧接着的是次之相关的文档。

search("which city is the capital of China?")

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

search("the economy engine in China")

快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索,Elasticsearch,AI,Elastic,elasticsearch,大数据,搜索引擎,数据库,全文检索

最后,源码在位置可以进行下载:https://github.com/liu-xiao-guo/semantic_search_es/blob/main/vector-search-using-gemini-elastic.ipynb文章来源地址https://www.toymoban.com/news/detail-811280.html

到了这里,关于快速入门:使用 Gemini Embeddings 和 Elasticsearch 进行向量搜索的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 一.Elasticsearch快速入门及使用

    Elasticsearch 是一个免费且开放的分布式搜索和分析引擎,适用于包括文本、数字、地理空间、结构化和非结构化数据等在内的所有类型的数据。 Elasticsearch 是全文搜索引擎的首选。它可以快速地 储存 、 检索 和 分析 海量数据。 相当于mysql你创建的某个数据库。 相当于mysql你

    2024年02月09日
    浏览(39)
  • elasticsearch快速入门,一篇就够了,上手使用!

    1.导入依赖 2.配置类 初始化配置bean,扔到ioc容器内 host链接–builder–RestHighLevelClient 3.测试类 1.导入依赖 2.导入前端素材 链接:https://pan.baidu.com/s/1M5uWdYsCZyzIAOcgcRkA_A 提取码:qk8p 复制这段内容后打开百度网盘手机App,操作更方便哦 3.application配置文件 4.先来测试一下controller和

    2023年04月08日
    浏览(30)
  • Elasticsearch:利用向量搜索进行音乐信息检索

    作者:Alex Salgado 欢迎来到音乐信息检索的未来,机器学习、向量数据库和音频数据分析融合在一起,带来令人兴奋的新可能性! 如果你对音乐数据分析领域感兴趣,或者只是热衷于技术如何彻底改变音乐行业,那么本指南适合你。 在这里,我们将带你踏上使用向量搜索方法

    2024年02月09日
    浏览(38)
  • Elasticsearch快速入门及结合Next.js案例使用

    🎉欢迎来到Java学习路线专栏~Elasticsearch快速入门及结合Next.js案例使用 ☆* o(≧▽≦)o *☆嗨~我是IT·陈寒🍹 ✨博客主页:IT·陈寒的博客 🎈该系列文章专栏:Java学习路线 📜其他专栏:Java学习路线 Java面试技巧 Java实战项目 AIGC人工智能 数据结构学习 🍹文章作者技术和水平有

    2024年02月03日
    浏览(29)
  • 使用Python进行网站页面开发——Django快速入门

    目录 一、项目的创建与运行 1.创建项目 2.运行  二、应用的创建和使用 1,创建一个应用程序 2.编写我们的第一个视图  三、项目的模型 1.连接MySQL数据库设置 2.创建模型 3.激活模型  4.使用(两种) (1)现在进入交互式的Python shell,并使用Django提供的免费API (2)在myapp应用的

    2023年04月08日
    浏览(42)
  • Elasticsearch 开放 inference API 增加了对 Cohere Embeddings 的支持

    作者:来自 Elastic Serena Chou, Jonathan Buttner, Dave Kyle 我们很高兴地宣布 Elasticsearch 现在支持 Cohere 嵌入! 发布此功能是与 Cohere 团队合作的一次伟大旅程,未来还会有更多合作。 Cohere 是生成式 AI 领域令人兴奋的创新者,我们很自豪能够让开发人员使用 Cohere 令人难以置信。 在

    2024年04月09日
    浏览(35)
  • 向量数据库:使用Elasticsearch实现向量数据存储与搜索

    Here’s the table of contents:   Elasticsearch在7.x的版本中支持 向量检索 。在向量函数的计算过程中,会对所有匹配的文档进行线性扫描。因此,查询预计时间会随着匹配文档的数量线性增长。出于这个原因,建议使用查询参数来限制匹配文档的数量(类似二次查找的逻辑,先使

    2024年02月07日
    浏览(44)
  • ElasticSearch学习之ElasticSearch快速入门实战

    1.先“分词” 2.倒排索引(前提是分词) ElasticSearch官网地址: 欢迎来到 Elastic — Elasticsearch 和 Kibana 的开发者 | Elastic https://www.elastic.co/cn/ 下载地址:https://www.elastic.co/cn/downloads/past-releases#elasticsearch 我在本地下载的是7.17.3版本  解压: 启动es之前别忘了配置环境变量:ES_JA

    2024年02月14日
    浏览(29)
  • ElasticSearch快速入门实战

    1.简介 创始人是Shay Banon(谢巴农),它是java开发,是凯源的企业级搜索引擎,能够实现实时搜索,特点是稳定、可靠、快速,并且安装使用方便。(内置JDK,不需要再安装JDK了) 客户端支持Java、.NET(C#)、PHP、Python、Ruby等主流语言。 目前使用es的公司 :京东等商城app,今日

    2023年04月09日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包