I've got an iOS app written in obj-c which takes a query typed into a search box and performs a multi match field query on the elasticsearch api. Can someone help with the formatting of the JSON request body? This is an example of the body of the get query I would like to format:
GET /test/data/_search
{
"min_score": 1.6,<br/>
"query": { <br/>
"multi_match": {<br/>
"query": "smith",<br/>
"fields": ["name", "surname"]<br/>
}<br/>
},<br/>
"_source": ["name", "surname", "address"]<br/>
}<br/>
In my code I have:
NSString *jsonRequest = [NSString stringWithFormat:@"{\"min_score\":\"1.6\",\"query\":{\"multi_match\":{\"name\",\"surname\":\"%@\"}},\"_source\":[\"name\",\"surname\",\"address\"]}",[self.searchTextField text]];
Where [self.searchTextField text] is the value taken from the search field.
But I get this error when back from ElasticSearch when I query:
reason = "Unexpected character (',' (code 44)): was expecting a colon to separate field name and value\n at [Source:
Just as a test, using a query to match just one field works fine, so it looks to be just a formatting issue.
Sorry forgot to add this is where I set the URL I post to with the JSON body:
[self postDataToUrl:@"http://localhost:9200/test/data/_search?pretty=true" withJson:jsonRequest];
this then passes to:
-(void)postDataToUrl:(NSString*)urlString withJson:(NSString*)jsonString
{
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"the final output is:%@",responseString);
NSError *lerror = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&lerror];
if (error != nil) {
NSLog(@"Error parsing JSON.");
}
else {
This is all works fine when I pass a regular match body e.g:
NSString *jsonRequest = [NSString stringWithFormat:@"{\"min_score\":\"1.6\",\"query\":{\"match\":{\"name\":\"%@\"}},\"_source\":[\"name\",\"surname\",\"address\"]}",[self.searchTextField text]];