跳至主要内容

Elasticsearch

使用 Elasticsearch 中托管的嵌入模型生成嵌入的演练

实例化 ElasticsearchEmbeddings 类最简单的方法是

  • 如果您使用的是 Elastic Cloud,则使用 from_credentials 构造函数
  • 或使用 from_es_connection 构造函数与任何 Elasticsearch 集群
!pip -q install langchain-elasticsearch
from langchain_elasticsearch import ElasticsearchEmbeddings
# Define the model ID
model_id = "your_model_id"

使用 from_credentials 测试

这需要一个 Elastic Cloud cloud_id

# Instantiate ElasticsearchEmbeddings using credentials
embeddings = ElasticsearchEmbeddings.from_credentials(
model_id,
es_cloud_id="your_cloud_id",
es_user="your_user",
es_password="your_password",
)
# Create embeddings for multiple documents
documents = [
"This is an example document.",
"Another example document to generate embeddings for.",
]
document_embeddings = embeddings.embed_documents(documents)
# Print document embeddings
for i, embedding in enumerate(document_embeddings):
print(f"Embedding for document {i+1}: {embedding}")
# Create an embedding for a single query
query = "This is a single query."
query_embedding = embeddings.embed_query(query)
# Print query embedding
print(f"Embedding for query: {query_embedding}")

使用现有的 Elasticsearch 客户端连接进行测试

这可用于任何 Elasticsearch 部署

# Create Elasticsearch connection
from elasticsearch import Elasticsearch

es_connection = Elasticsearch(
hosts=["https://es_cluster_url:port"], basic_auth=("user", "password")
)
# Instantiate ElasticsearchEmbeddings using es_connection
embeddings = ElasticsearchEmbeddings.from_es_connection(
model_id,
es_connection,
)
# Create embeddings for multiple documents
documents = [
"This is an example document.",
"Another example document to generate embeddings for.",
]
document_embeddings = embeddings.embed_documents(documents)
# Print document embeddings
for i, embedding in enumerate(document_embeddings):
print(f"Embedding for document {i+1}: {embedding}")
# Create an embedding for a single query
query = "This is a single query."
query_embedding = embeddings.embed_query(query)
# Print query embedding
print(f"Embedding for query: {query_embedding}")

此页面是否有帮助?


您还可以留下详细的反馈 在 GitHub 上.