# Implementing machine learning API in Rust using elasticsearch8.4.0-alpha.1 library

**URL:** <https://discuss.elastic.co/t/implementing-machine-learning-api-in-rust-using-elasticsearch8-4-0-alpha-1-library/337770>\
**Category:** Elasticsearch\
**Tags:** elastic-stack-machine-learning, language-clients\
**Created:** [July 6, 2023, 9:13am UTC](https://discuss.elastic.co/t/implementing-machine-learning-api-in-rust-using-elasticsearch8-4-0-alpha-1-library/337770 "2023-07-06T09:13:37Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![aniket\_mandhare](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/aniket_mandhare/32/122986_2.png) [@aniket\_mandhare](https://discuss.elastic.co/u/aniket_mandhare)\
**Post date:** [July 6, 2023, 9:13am UTC](https://discuss.elastic.co/t/implementing-machine-learning-api-in-rust-using-elasticsearch8-4-0-alpha-1-library/337770/1 "2023-07-06T09:13:37Z")

</div>

Hey folks, I am trying to implement machine learning API in **Rust** programming language using **elasticsearch8.4.0-alpha.1** library and now I am stuck. I want to use ML model which is already imported in Elasticsearch which converts text into vector. Please help me out.

```auto
ub async fn vector_search(data: web::Json<Value>) -> Result<HttpResponse, CustomError> {
    let client = get_client().unwrap();
    let infer_response = client
    .ml().get_trained_models(elasticsearch::ml::Ml::get_trained_models())
    .send()
    .await
    .unwrap();
    let response_id_body = infer_response.json::<Value>().await.unwrap();
    Ok(HttpResponse::Ok().json(json!(response_id_body)))
    
}

```

---

<div class="post-metadata">

**Author:** ![dkyle](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dkyle/32/59114_2.png) [@dkyle](https://discuss.elastic.co/u/dkyle)\
**Post date:** [July 7, 2023, 8:00am UTC](https://discuss.elastic.co/t/implementing-machine-learning-api-in-rust-using-elasticsearch8-4-0-alpha-1-library/337770/2 "2023-07-07T08:00:15Z")

</div>

I can't help you with the Rust programming sorry but you want to call the \_infer API. GET Trained models returns the model configurations

Here's a blog that describes using Text Embeddings in Elasticsearch: [How to deploy NLP: Text Embeddings and Vector Search | Elastic Blog](https://www.elastic.co/blog/how-to-deploy-nlp-text-embeddings-and-vector-search)

---

<div class="post-metadata">

**Author:** ![aniket\_mandhare](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/aniket_mandhare/32/122986_2.png) [@aniket\_mandhare](https://discuss.elastic.co/u/aniket_mandhare)\
**Post date:** [July 11, 2023, 6:11am UTC](https://discuss.elastic.co/t/implementing-machine-learning-api-in-rust-using-elasticsearch8-4-0-alpha-1-library/337770/3 "2023-07-11T06:11:23Z")

</div>

Hello @dkyle , thanks for looking into this, but I got the solution. Actually, I found two solutions and one of them worked for me.  
First Solution: The following function returns the vector field for text which is passed through argument.

```auto
pub async fn get_vector(str:String) -> Value {
    let client = reqwest::Client::new();
    let res = client
        .post("http://localhost:9200/_ml/trained_models/sentence-transformers__clip-vit-b-32-multilingual-v1/_infer")
        .basic_auth(env::var("elasticsearch_username").expect("Please set username in .env"), Some(env::var("elasticsearch_password").expect("Please set password in .env")))
        .json(&json!({
            "docs": [{"text_field": str}]
        }))
        .send()
        .await
        .unwrap();
    let response_body = res.json::<Value>().await.unwrap();
    let predicted_value = json!(response_body["inference_results"][0]["predicted_value"]);
    predicted_value
}

```

Second Solution: I found this solution online but never worked for me.

- Define the get\_client function to create an Elasticsearch client instance. Make sure to replace `http://localhost:9200` with the appropriate Elasticsearch URL:

```auto
fn get_client() -> Result<Elasticsearch, Box<dyn std::error::Error>> {
    let builder = elasticsearch::Elasticsearch::default();
    let client = builder.url("http://localhost:9200").build()?;
    Ok(client)
}

```

- Implement the vector\_search function:

```auto
pub async fn vector_search(data: web::Json<Value>) -> Result<HttpResponse, CustomError> {
    let client = get_client()?;
    
    // Retrieve the trained models
    let trained_models_response = client.ml().get_trained_models().send().await?;
    let trained_models = trained_models_response.json::<Value>().await?;
    
    // Choose the desired model ID
    let model_id = "your_model_id";
    
    // Perform the vector inference
    let inference_response = client
        .ml()
        .infer_vector(elasticsearch::ml::MlInferVectorParts::IndexId(model_id))
        .body(json!({
            "docs": [
                {
                    "field": "your_text_field",
                    "text": "your_text_data"
                }
            ]
        }))
        .send()
        .await?;
        
    let inferred_vectors = inference_response.json::<Value>().await?;
    
    Ok(HttpResponse::Ok().json(json!(inferred_vectors)))
}

```

Replace "your\_model\_id" with the ID of the trained model you want to use. Replace "your\_text\_field" with the name of the field containing the text data in your Elasticsearch index. Replace "your\_text\_data" with the actual text you want to convert into a vector.  
**Note** : You need platinum version of Elasticsearch

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [August 8, 2023, 6:11am UTC](https://discuss.elastic.co/t/implementing-machine-learning-api-in-rust-using-elasticsearch8-4-0-alpha-1-library/337770/4 "2023-08-08T06:11:51Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
