Reputation: 4863
I need to make an Elastic Search query with Ajax. What I'm trying to do is search for a specific category name, and return the list of names associated with that category. The structure in Elastic Search is that each _source has a name fields (the name of the category), and an items fields. It also has name.raw so that I can search by exact name.
This is my request:
var query = {
query: {
filtered: {
filter: {
term: { "name.raw": category }
}
}
}
}
$.ajax({
url: "http://192.168.0.240:9200/dropdowns/category/_search",
type: 'post',
dataType: 'json',
success: function(data) {
alert("Success");
},
error: function(data) {
// should be only one item in hits
$(data.hits.hits).each(function(index, hit) {
alert(hit._source.items);
});
},
data: query
});
For now, I'm trying to simply get it to work enough to alert me to the items in the hit. I'm getting a 400 Bad Request error. What's wrong with my Ajax call?
Upvotes: 0
Views: 8664
Reputation: 491
You should be able to send the query in the URL using a GET method, with this syntax:
var query = '{"query":{"filtered":{"filter:{"term":{"name.raw": category}}}}}';
$.ajax({
url: `http://192.168.0.240:9200/dropdowns/category/_search?
source_content_type=application/json&source=${query}`,
success: function(data) {
console.log(data);
}
});
Upvotes: 2
Reputation: 683
The HTTP libraries of certain languages (notably Javascript) don’t allow GET requests to have a request body.
See this: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/_empty_search.html
So I think it's correct to use POST method here, you simply forget to stringify the request body.
Upvotes: 1
Reputation: 4863
With help from Jonathon Lerner, I figured out that the problem with my query was that it had to be stringified. So, I simply changed it to
data : JSON.stringify(query)
Upvotes: 2
Reputation: 450
Using the following code:
var query = {
query: {
filtered: {
filter: {
term: { "name.raw": category }
}
}
}
};
$.ajax({
url: "http://192.168.0.240:9200/dropdowns/category/_search",
type: 'GET',
dataType: 'json',
success: function(data) {
console.log('Success');
$(data.hits.hits).each(function(index, hit) {
console.log(hit._source.items);
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
},
data: query
});
you should be able to debug the problem with your query in the Javascript Console, as well as see successful output. Here are some directions on how to see the JS console in different browsers: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
Edit: It seems like those directions are for Windows specifically. I know that on Mac, Command+Option+j opens the Chrome JS console. Im sure if your browser/OS isnt covered here you can find the correct shortcut on Google.
Upvotes: 1