How to do an ElasticSearch using REST request body method and get the returned json formatted / pretty? - elasticsearch

In issuing a search request, via REST Request Body method, such as
GET /bank/_search
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
]
}
is there a parameter that can be added anywhere to request the returned response body's json be formatted/pretty ?
The same search using REST Request URI enables to do that, like
GET /bank/_search?q=*&sort=account_number:asc&pretty
How to achieve the same using REST request body ?
Using ElasticSearch.NET's low level api, one have no control over the REST call, and can only provide the POST json.
var esClient = new ElasticLowLevelClient(_connectionSettings);
//postDataJson is the json depicted in the question's body
var postData = PostData.String(postDataJson);
var response = esClient.Search<StringResponse>("myIndex", postData);
One can send a third parameter, a SearchRequestParameters object, I can't find any property there for that.

You need to add to your request pretty=true
Like that:
GET /bank/_search?q=*&sort=account_number:asc&pretty=true
for more reference check here
EDIT
I didn't understand you at first, the pretty should be in the header of the request.
Try like that:
GET /bank/_search?pretty=true
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
]
}
EDIT 2
If you are using elstic.NET and you want too achieve pretty Jason.
You need to configure it in the connection.
Here is the method you should use(it's in the classConnectionConfiguration : ConnectionConfiguration<ConnectionConfiguration>):
/// <summary>
/// Forces all requests to have ?pretty=true querystring parameter appended,
/// causing Elasticsearch to return formatted JSON.
/// Also forces the client to send out formatted JSON. Defaults to <c>false</c>
/// </summary>
public T PrettyJson(bool b = true) => Assign(a =>
{
this._prettyJson = b;
const string key = "pretty";
if (!b && this._queryString[key] != null) this._queryString.Remove(key);
else if (b && this._queryString[key] == null)
this.GlobalQueryStringParameters(new NameValueCollection { { key, "true" } });
});
Here you can see the git

Related

Aws-appSync Resolver mapping templte getting sliced data

Currently my data return from graphql query is in format and have 1200 questions from my http data source and want to return only first 10 through graphl in response mapping template.
{
"data": {
"questions":[
{
questions:"ques 1"
},
{
questions:"ques 2"
}, ....
]
}
}
My response mapping template code look likes this for slicing on aws appsycn(VTL direct resolver)
#if($ctx.result.statusCode == 200)
$ctx.result.body.data.questions.slice(0,10)
But getting error message:
Unable to convert $ctx.result.body.data.questions.slice(0,10)\n to Object"
i have tries to return via $util.toJson() also, but still facing same error.

Springdocs: Specifying an explicit type for Paged responses

I'm working on a "global search" for my application.
Currently, I'm using hibernate-search to search for instances of multiple different objects and return them to the user.
The relevant code looks as follows:
Search.session(entityManager)
.search(ModelA.classs, ModelB.class)
.where(...)
.sort(...)
.fetch(skip, count);
Skip and count are calculated based on a Pageable and the result is used to create an instance of Page, which will be returned to the controller.
This works as I'd expect, however, the types generated by swagger-docs obviously doesn't know, what the type within the Page is, and therefore uses Object.
I'd like to expose the correct types, as I use them to generate the types for the frontend application.
I was able to set the type to an array, when overwriting the schema like this:
#ArraySchema(schema = #Schema(anyOf = {ModelA.class, ModelB.class}))
public Page<?> search(Pageable pageable) {
However, this just disregards the Page and also isn't correct.
The next thing I tried is extending the PageImpl, overwriting the getContent method, and specifying the same schema on this method, but this wasn't included in the output at all.
Next was implementing Page<T> myself (and later removing the implements reference to Page<T>) and specifying the same schema on getContent, iterator, and the field itself, but also to no effect.
How do I tell spring-docs, what the content of the resulting Page might be?
I stumbled upon this when trying to solve a similar problem
Inspired from this thread Springdoc with a generic return type i came up with the following solution, and it seems to apply to your case also. Code examples are in Kotlin.
I introduced a stub class that will just act as the Schema for the response:
private class PageModel(
#Schema(oneOf = [ModelA::class, ModelB::class]))
content: List<Object>
): PageImpl<Object>(content)
Then i annotated my Controller like this:
#Operation(
responses = [
ApiResponse(
responseCode = "200",
content = [Content(schema = Schema(implementation = PageModel::class))]
)
]
)
fun getPage(pageable: Pageable): Page<Object>
This generated this api response:
"PageModel": {
"properties": {
"content": {
"items": {
"oneOf": [
{
"$ref": "#/components/schemas/ModelA"
},
{
"$ref": "#/components/schemas/ModelB"
}
],
"type": "object"
},
"type": "array"
},
... -> more page stuff from spring's PageImpl<>
And in the "responses" section for the api call:
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PageModel"
}
}
},
"description": "OK"
}
All generated openapi doc is similar to the autogenerated json when returning a Page, it just rewrites the "content" array property to have a specific type.

Quarkus calling Rest API with dynamic endpoint

I used the micro profile to make a call to a specific API, it happens that this call gives me a list of URLs and I have to make a call for each URL returned.
My objective is call all of these URL e verify HTTP status returned.
"ApiResources": [
{
"ApiFamilyType": "products-services",
"ApiVersion": 1,
"ApiResourceId": "d33ff8af-5a1b-4b43-90d4-34237997d080",
"ApiDiscoveryEndpoints": [
{
"ApiEndpoint": "https://api.yyyyyyyy/v1/personal-accounts"
},
{
"ApiEndpoint": "https://api.xxxxxxx/business-accounts"
}
}
]

ElasticSearch NEST Executing raw Query DSL

I'm trying to create the simplest proxy possible in an API to execute searches on ElasticSearch nodes. The only reason for the proxy to be there is to "hide" the credentials and abstract ES from the API endpoint.
Using Nest.ElasticClient, is there a way to execute a raw string query?
Example query that is valid in vanilla ES:
{
"query": {
"fuzzy": { "title": "potato" }
}
}
In my API, I tried Deserializing the raw string into a SearchRequest, but it fails. I'm assuming it cannot deserialize the field:
var req = m_ElasticClient.Serializer.Deserialize<SearchRequest>(p_RequestBody);
var res = m_ElasticClient.Search<T>(req);
return m_ElasticClient.Serializer.SerializeToString(res);
System.InvalidCastException: Invalid cast from 'System.String' to 'Newtonsoft.Json.Linq.JObject'.
Is there a way to just forward the raw string query to ES and return the string response? I tried using the LowLevel.Search method without luck.
NEST does not support deserializing the short form of "field_name" : "your_value" of the Elasticsearch Query DSL, but it does support the long form "field_name" : { "value" : "your_value" }, so the following works
var client = new ElasticClient();
var json = #"{
""query"": {
""fuzzy"": {
""title"": {
""value"": ""potato""
}
}
}
}";
SearchRequest searchRequest;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
searchRequest = client.Serializer.Deserialize<SearchRequest>(stream);
}
As Rob has answered, NEST also supports supplying a raw json string as a query
Yes, you can do this with NEST, check out the following
var searchResponse = client.Search<object>(s => s
.Type("type").Query(q => q.Raw(#"{""match_all"":{}}")));
Hope that helps.

how to tell rest post data is invalid in spring

I have a post data request as the following,
{
"doctorId":1,
"userId":29,
"sampleConditions":[
{
"conditionId":"14",
"conditionName":"Acne",
"conditionDate":"2017-01-31"
}
],
"labOrder":{
"testId" : [1,2,3]
}
}
what happens, if the client gives the incorrect key
"sampleConditionss":[
{
"conditionId":"14",
"conditionName":"Acne",
"conditionDate":"2017-01-31"
}
],
Instead of giving sampleConditions, the client have sent the request as sampleConditionss.
How can i handle the request,
When you are using springs the spring framework will return 400 and you need not do anything here

Resources