Ajax query format with Elasticsearch

I am trying to make a post request with AJAX to my elasticsearch index. The cURL result is:

[~]$ curl -XGET 'http://localhost:9200/firebase/_search?q=song:i%20am%20in'

{"took":172,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2,"max_score":0.82749283,"hits":[{"_index":"firebase","_type":"song","_id":"0001","_score":0.82749283,"_source":{"song":"i am in california","song_name":"hello","song_url":"https://s3.ap-south-1.amazonaws.com/songapp-dump/media/songs/Adele_-_Hello-_i_am_in_california.mp3"}},{"_index":"firebase","_type":"song","_id":"0002","_score":0.28582606,"_source":{"song":"i must have called a thousand times","song_name":"hello","song_url":"https://s3.ap-south-1.amazonaws.com/songapp-dump/media/songs/Adele_-_Hello-_i_must_have_called_a_thousand_times.mp3"}}]}} 

Browser result is:enter image description hereThis is also working correctly. Meaning the index has been created and cURL/ GET is able to get the result.

When I am trying to have an AJAX request do the same, I am struggling with the query format probably. I am not able to figure out.

Ajax.js

$(function() {
    $('#message').keyup(function() {
        // console.log(JSON.stringify());
        var data = {
                'song': $('#message').val()
            };
        console.log(JSON.stringify(data));
        $.ajax({
            type: "POST",
            url: "http://localhost:9200/firebase/_search",
            contentType: 'application/json',
            // data: {
            //     'q': $('#message').val()
            // },
            data: JSON.stringify(data),
            success: searchSuccess,
            dataType: 'jsonp'
        });

    });

});

The console logs the following error: enter image description here

Basically it's a 400 Bad Request error. I am not able to figure out if there is something wrong with my query or the way Ajax request is being created. Why am I having callback issues! Any help would be appreciated. I have scoured the web on this issue and have tried various combinations as well.

1 answer

  • answered 2017-06-17 18:47 styfle

    Change the method to GET and dateType to json. Also the querystring requires a q parameter.

         var data = {
             'q': 'song:' + $('#message').val()
         };
    
         $.ajax({
            type: "GET",
            url: "http://localhost:9200/firebase/_search",
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: searchSuccess,
            dataType: 'json'
        });