使用elasticsearch8.4.0-alpha.1库在Rust中实现机器学习API

lsmepo6l  于 2024-01-08  发布在  ElasticSearch
关注(0)|答案(1)|浏览(126)

我尝试使用elasticsearch8.4.0-alpha.1库在Rust编程语言中实现机器学习API,现在卡住了。我想使用已经在Elasticsearch中导入的ML模型,它将文本转换为矢量。请帮帮我

  1. pub async fn vector_search(data: web::Json<Value>) -> Result<HttpResponse, CustomError> {
  2. let client = get_client().unwrap();
  3. let infer_response = client
  4. .ml().get_trained_models(elasticsearch::ml::Ml::get_trained_models())
  5. .send()
  6. .await
  7. .unwrap();
  8. let response_id_body = infer_response.json::<Value>().await.unwrap();
  9. Ok(HttpResponse::Ok().json(json!(response_id_body)))
  10. }

字符串

jrcvhitl

jrcvhitl1#

要在Elasticsearch中使用预训练的ML模型将文本转换为矢量,以下步骤对我来说很有效:

  • 确保你已经将Elasticsearch Rust crate添加到Cargo.toml中的项目依赖项中:
  1. [dependencies]
  2. elasticsearch = "8.4.0-alpha.1"

字符串

  • 在Rust文件中导入必要的模块:
  1. use elasticsearch::Elasticsearch;
  2. use serde_json::{json, Value};
  3. use actix_web::{web, HttpResponse};

  • 定义get_client函数来创建Elasticsearch客户端示例。确保将http://localhost:9200替换为适当的Elasticsearch URL:
  1. fn get_client() -> Result<Elasticsearch, Box<dyn std::error::Error>> {
  2. let builder = elasticsearch::Elasticsearch::default();
  3. let client = builder.url("http://localhost:9200").build()?;
  4. Ok(client)
  5. }

  • 执行vector_search函数:
  1. pub async fn vector_search(data: web::Json<Value>) -> Result<HttpResponse, CustomError> {
  2. let client = get_client()?;
  3. // Retrieve the trained models
  4. let trained_models_response = client.ml().get_trained_models().send().await?;
  5. let trained_models = trained_models_response.json::<Value>().await?;
  6. // Choose the desired model ID
  7. let model_id = "your_model_id";
  8. // Perform the vector inference
  9. let inference_response = client
  10. .ml()
  11. .infer_vector(elasticsearch::ml::MlInferVectorParts::IndexId(model_id))
  12. .body(json!({
  13. "docs": [
  14. {
  15. "field": "your_text_field",
  16. "text": "your_text_data"
  17. }
  18. ]
  19. }))
  20. .send()
  21. .await?;
  22. let inferred_vectors = inference_response.json::<Value>().await?;
  23. Ok(HttpResponse::Ok().json(json!(inferred_vectors)))
  24. }


将“your_model_id”替换为您想要使用的训练模型的ID。将“your_text_field”替换为Elasticsearch索引中包含文本数据的字段的名称。将“your_text_data”替换为要转换为矢量的实际文本。

展开查看全部

相关问题