elastic / elasticsearch-rs

Official Elasticsearch Rust Client
https://www.elastic.co/guide/en/elasticsearch/client/rust-api/current/index.html
Apache License 2.0
702 stars 72 forks source link

Best practice for converting search results to Rust structs? #79

Closed Jasperav closed 4 years ago

Jasperav commented 4 years ago

When using the search api, the queried objects are in an array inside "hits" and another "hits". Furthermore, the actual objects are again nested inside a "_source" object. So to extract the data from a search, I have this code:

let value = response.read_body::<Value>().unwrap();

let mut hits = value["hits"]["hits"]
    .as_array()
    .unwrap()
    .clone();

if hits.is_empty() {
    return Ok(vec![])
}

Ok(hits
    .into_iter()
    .map(|e| e["_source"].clone())
    .map(|e| serde_json::from_value(e).unwrap())
    .collect::<BResult<_>>()?)

This looks like code that can be somewhere in this library (else everyone needs to write something like this). Is there a standard way of doing what I am doing?

russcam commented 4 years ago

The example you show is the way I would recommend for now.

What would be really useful here is a SearchResponse<T> struct that the response from the search API is deserialized into. This is something that we would like to provide eventually, but it is a sizeable undertaking, more so for more complex responses like search! I'm going to close this issue in order to discuss on #75 as it is related to this issue.