I have been trying to conduct a multi-search (where I am able to send several json objects at once) but have failed so far.
This request is going to an Elasticsearch server but even if you don't know what that is you can still help.
I want to have a request body that looks like this:
{"index": "superheroes"}
{"query": {"term": {"name": {"term": "hulk"}}}}
{"index": "superheroes"}
{"query": {"term": {"name": {"term": "spiderman"}}}}
{"index": "superheroes"}
{"query": {"term": {"name": {"term": "ant man"}}}}
Notice the JSON objects are not wrapped with an array.
If I send that exact block via a client such as Postman, I get the desired output from the server.
Here is what I am doing in Rust to send that request:
let mut request_pieces: Vec<serde_json::Value> = Vec::new();
for name in names {
request_pieces.push(json!({"index": "superheroes"}));
request_pieces.push(json!({"query": {"term": {"name": {"term": name}}}}));
}
let search_body: Value = json!(request_pieces);
println!("{:?}", search_body);
When I send that I get an error from the server, it makes sense as it is inside an array and the server is not expecting that, what I am sending to the server looks like the following:
Array([
Object({
"index": String(
"superheroes",
),
}),
Object({
"query": Object({
"term": Object({
"name": Object({
"term": String(
"hulk",
),
}),
}),
}),
}),
Object({
"index": String(
"superheroes",
),
}),
Object({
"query": Object({
"term": Object({
"name": Object({
"term": String(
"spiderman",
),
}),
}),
}),
}),
Object({
"index": String(
"superheroes",
),
}),
Object({
"query": Object({
"term": Object({
"name": Object({
"term": String(
"ant man",
),
}),
}),
}),
}),
])
How can I send a request like the one at the very top? where the JSON objects are separated.
By the way, a way this was achieved in other programming languages was by making it all a string, but in Rust it is very challenging going to do so.
CodePudding user response:
When you have a vector of json requests, instead of encoding that into a json string, you can directly obtain what you want:
let mut request_pieces = Vec::new();
for name in names {
request_pieces.push(json!({"index": "superheroes"}).to_string());
request_pieces.push(json!({"query": {"term": {"word": {"term": name}}}}).to_string());
}
let search_body = request_pieces.join("\n");
println!("{}", search_body);