How should I customize my search result in vespa? - vespa

I have a search result like whcih is given below :
{
"root": {
"id": "toplevel",
"relevance": 1,
"fields": {
"totalCount": 20
},
"coverage": {
"coverage": 100,
"documents": 20,
"full": true,
"nodes": 1,
"results": 1,
"resultsFull": 1
},
"children": [{
"id": "group:string:Jones",
"relevance": 9870,
"value": "Jones",
"fields": {
"sum(price)": 39816
}
},
{
"id": "group:string:Brown",
"relevance": 8000,
"value": "Brown",
"fields": {
"sum(price)": 20537
}
}
]
}
}
I do not want fields and coverage in my search results. How can I achieve this?. And also I want to change status according to error with error message. How can I do this? Please help.

Response payload: You can create your own renderer to control the returned format: https://docs.vespa.ai/documentation/result-rendering.html
HTTP status code: The rules for determining the status code to return are:
If the Result contains no errors (Result.hits().getError()==null): 200 OK is returned.
If the Result contains errors and no regular hits: If the error code of any ErrorMessage in the Result (Result.hits().getErrorHit().errorIterator()) is a "WEB SERVICE ERROR CODE", the first of those is returned. Otherwise, if it is a "HTTP COMPATIBLE ERROR CODE", the mapping of it is returned. Otherwise 500 INTERNAL_SERVER_ERROR is returned.
If the Result contains errors and also contains valid hits: The same as above, but 200 OK is returned by default instead of 500.
WEB SERVICE ERROR CODES:
200, 301, 302, 307, 400, 401, 403, 404, 405, 406, 408, 428, 429, 431, 500, 501, 502, 511
HTTP COMPATIBLE ERROR CODES:
com.yahoo.container.protect.Error.BAD_REQUEST -> Http code 400
com.yahoo.container.protect.Error.UNAUTHORIZED -> Http code 401
com.yahoo.container.protect.Error.FORBIDDEN -> Http code 403
com.yahoo.container.protect.Error.NOT_FOUND -> Http code 404
com.yahoo.container.protect.Error.INTERNAL_SERVER_ERROR -> Http code 500
com.yahoo.container.protect.Error.INSUFFICIENT_STORAGE -> Http code 507
With this information, you can write a Searcher component (https://docs.vespa.ai/documentation/searcher-development.html) which sets an ErrorMessage in the Result corresponding to the HTTP status you want.
For a real world example see e.g the rate limiting Searcher bundled in Vespa: https://github.com/vespa-engine/vespa/blob/master/container-search/src/main/java/com/yahoo/search/searchers/RateLimitingSearcher.java#L133

To customize results you can use a result renderer. Please take a look at https://docs.vespa.ai/documentation/result-rendering.html which should be complete with examples.

Related

How to I can custom exception message from FileInterceptor?

I want custom exception from FileInterceptor.
Here my lines of code:
#Post('single')
#UseInterceptors(
FileInterceptor('file', { limits: {
files: 1
}}),
)
async uploadFile(#UploadedFile() file, #GetUser('id') userId: number, #Body() dto) {
this.logger.log('Upload file');
file.createdBy = userId;
file.oldFileName = dto.oldFileName;
return this.client.send('upload_file', file);
}
I pass in body with file attribute, it is 1 array files (there are 2 files)
I got message:
{
"response": {
"statusCode": 400,
"message": "Too many files",
"error": "Bad Request"
},
"status": 400,
"message": "Too many files",
"name": "BadRequestException"
}
I want custom that message like to this:
{
"code": 400,
"message": "Too many files"
}
Please help me a solution. Thanks
you can try this to custom your error

Discord api ignores the 'file' element

I've got a problem with using requests in python to upload files.
non-working code:
import requests
url = 'https://discord.com/api/v9/channels/XXXXX/messages'
headers = {
'authorization': 'XXXXX'
}
data = {
'file': open('test.png', 'rb')
}
r = requests.post(url=url, headers=headers, data=data)
print(r)
print(r.text)
This is the response I get:
<Response [400]>
{"message": "Cannot send an empty message", "code": 50006}
so I tried adding to data "content": "Whoas"
data = {
'file': open('test.png', 'rb'),
"content": "Whoas"
}
Which will now at least send the message, but without the file.
Here's the response I get:
<Response [200]>
{"id": "XXXXX", "type": 0, "content": "Whoas", "channel_id": "XXXXX", "author": {"id": "XXXXX", "username": "XXXXX", "avatar": "XXXXX", "discriminator": "2885", "public_flags": 0}, "attachments": [], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-05-22T09:08:47.061000+00:00", "edited_timestamp": null, "flags": 0, "components": [], "referenced_message": null}
I'm most likely just not understanding the discord API documentation (https://discord.com/developers/docs/resources/channel#create-message), which unfortunately doesn't go into detail about how to upload a file.
I've tried using the module discord.py with discord.File('test.png') but this method isn't giving back the link to the uploaded file, which I need.
If anyone has any idea how to get this to work, it would be really appreciated!
From what I can tell here... you’re using API calls to operate a bot. In reality, this is a very complex process which is why we have libraries such as discord.py to make everything simpler. If you’re looking to create a bot, you should totally check out their documentation.

No suitable constructor google app engine

I'm trying to insert data in my google datastore, so I send this request throught google API explorer:
POST https://local-sport-meeting-app.appspot.com/_ah/api/localSportMeetingApi/v1/rencontre
Content-Type: application/json
X-JavaScript-User-Agent: Google APIs Explorer
{
"date": {
"day": 30,
"hour": 20,
"minute": 15,
"month": 11,
"year": 2014
},
"idComp": "5153049148391424",
"idParticipant2": "5664902681198592",
"idPartiticpant1": "5734055144325120",
"latitude": 3.105024,
"lieu": "STADE MARCEL MICHELIN\"",
"longitude": 45.789907
}
but this is returning this error:
400 Bad Request
- Show headers -
{
"error": {
"errors": [
{
"domain": "global",
"reason": "badRequest",
"message": "com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.iutclermont.lpmobile.localsportmeeting.backend.DatePerso]: can not instantiate from JSON object (need to add/enable type information?)\n at [Source: N/A; line: -1, column: -1] (through reference chain: com.iutclermont.lpmobile.localsportmeeting.backend.Rencontre[\"date\"])"
}
],
"code": 400,
"message": "com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.iutclermont.lpmobile.localsportmeeting.backend.DatePerso]: can not instantiate from JSON object (need to add/enable type information?)\n at [Source: N/A; line: -1, column: -1] (through reference chain: com.iutclermont.lpmobile.localsportmeeting.backend.Rencontre[\"date\"])"
}
}
I generate my entity with Objectify and an app engine module in android studio and I have an empty constructor as requested by Objectify
Do anyone already have this problem or know how to fix it.
Thanks.

dev_appserver.py locally rejects PATCH requests but accepts it on deployed

I've got an app based on djangoappengine, Backbone.js and Django REST Framework that uses PATCH requests to update models via {patch: true} on a model.save call.
I've found that when testing locally the dev_appserver returns:
ERROR 2014-02-19 04:37:04,531 dev_appserver.py:3081] code 501, message Unsupported method ('PATCH')
INFO 2014-02-19 04:37:04,532 dev_appserver.py:3090] "PATCH /api/posts/5707702298738688 HTTP/1.1" 501 -
Yet when I deploy it and access it through appspot the server happily accepts the request. Which forces me to deploy every time I make a change and want to test it.
I'm running the latests version (1.89) of the Python SDK, and found and old fixed issue that seems to tackle it but it seems other people have had it.
I tried this patch but it didn't make a difference. I don't understand why the development server would reject them and not the production server, is there something I need to change?
Thanks.
To update a resource, you can use POST with the x-http-method-override to patch. This is a valid RESTful operation and using POST will be more compatible with firewall and older user agents. The data in the request should indicate what is to be updated.
var url = '/api/posts/5707702298738688'
var patch_ops = [
{ "op": "replace", "path": "/properties/", "author": text}
{ "op": "add", "path": "/replies/", {"author": text, "comment":"blah"}}
/*
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
*/
];
var xhr = jQuery.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("X-HTTP-Method-Override", "PATCH");
},
url: url,
data: my_json_string,
dataType:"json",
success: function(data) {
return data;
},
error: function(xhr, textStatus, error){
return error;
}
});
Server handler:
def post(self, object_name):
if self.request.headers['x-http-method-override'] == 'PATCH':
# update according to patch operations
patch_ops_str= self.request.body.decode('utf-8')
try:
patch_ops = json.loads(new_area_geojson_str)
except:
self.response.set_status(400)
return self.response.out.write('{"status": "error", "reason": "JSON Parse error" }')
else:
self.response.set_status(405)
return self.response.out.write('{"status": "error", "reason": "post not accepted without x-http-method-override to PATCH" }')
Adapted from Please do not patch like an idiot

Which callback for XMLHttpRequest status 0?

I'm occasionally seeing a failed XMLHttpRequest.send(). From Chrome's network panel I'm seeing a status of 0 - see below from the .har file. The code that runs the send() succeeds >99% of the time, but very occasionally (~ 1/300) it returns 0.
My question is: how do I catch this? Is there are callback that will catch it?
I'm currently using onload and onerror:
var xhr = new XMLHttpRequest();
xhr.onload = function(){};
xhr.onerror = function(){};
Neither of those are being called, so it's failing silently.
A few other things to note:
There is no evidence of the request in the server logs
There are no error messages in Chrome's console
The server is google app engine
Here's the .har file output. ##=redacted.
{
"startedDateTime": "2013-03-30T23:52:20.972Z",
"time": 97,
"request": {
"method": "GET",
"url": "https://www.#######.com/project/auth_upload?to_sign=PUT%0A%0A%0A%0Ax-amz-date%3ASat%2C%2030%20Mar%202013%2023%3A52%3A20%20GMT%0A/s3.#####.com/######.mp4%3FpartNumber%3D50%26uploadId%3D#################.w--&asset_id=#############&project_id=###########",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Referer",
"value": "https://www.######.com/console/###########"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.152 Safari/537.22"
}
],
"queryString": [
{
"name": "to_sign",
"value": "PUT%0A%0A%0A%0Ax-amz-date%3ASat%2C%2030%20Mar%202013%2023%3A52%3A20%20GMT%0A/s3.#######.com/############.mp4%3FpartNumber%3D50%26uploadId%3D##############"
},
{
"name": "asset_id",
"value": "###########"
},
{
"name": "project_id",
"value": "###############"
}
],
"cookies": [],
"headersSize": 595,
"bodySize": 0
},
"response": {
"status": 0,
"statusText": "",
"httpVersion": "HTTP/1.1",
"headers": [],
"cookies": [],
"content": {
"size": 0,
"compression": 0
},
"redirectURL": "",
"headersSize": 13,
"bodySize": 0
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": -1,
"wait": -1,
"receive": null,
"ssl": -1
}
}
thanks,
tom
It seems that statusCode 0 indicates that response is empty even headers are not sent, that is something hard to figure out and you need to find it out yourself
but you said that the response doesn't arrive in your functions is because you are using load and error events for listening for the response, and actually you shouldn't entirely depend on those two errors, consider as case where timeout has occured before your request gets completed then 'timeout' event will be fired not 'error'
Instead you should use readystatechange event that will be called on every state change of request and you can also keep track of timeouts or errors related to no response received
httpRequest.onreadystatechange = stateChangeHandler;
stateChangeHandler = function() {
// The readyState can be 4 values:
// 0 - uninitialized
// 1 - loading
// 2 - loaded
// 3 - interactive
// 4 - complete
//
// readyState 0 - 3 can be completely ignored by us, as they are only updates
// about the current progress. Only on readyState 4, should we continue and
// start checking for the response status.
if (xmlHttpRequest.readyState != 4) {
return;
}
// Check HTTP Response code
if (xmlHttpRequest.status != 200) {
// response is ok process it
} else {
// there was some error
}
}
Reference:
https://developer.mozilla.org/en-US/docs/HTTP#HTTP_Response_Codes
http://www.w3.org/TR/XMLHttpRequest/#event-xhr-readystatechange
http://msdn.microsoft.com/en-us//library/ms534361%28en-us,VS.85%29.aspx
http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute

Resources