Elasticsearch

时间:2017-06-17 18:47:05

标签: javascript jquery ajax curl elasticsearch

我正在尝试使用AJAX向我的弹性搜索索引发布帖子请求。 cURL结果是:

[~]$ 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"}}]}} 

浏览器结果为:enter image description here这也正常工作。意味着已创建索引并且cURL / GET能够获得结果。

当我试图让AJAX请求做同样的事情时,我可能正在努力寻找查询格式。我无法理解。

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'
        });

    });

});

控制台记录以下错误: enter image description here

基本上它是400 Bad Request错误。我无法弄清楚我的查询或Ajax请求的创建方式是否有问题。为什么我有回调问题!任何帮助,将不胜感激。我已经在这个问题上搜索了网络,并尝试了各种组合。

1 个答案:

答案 0 :(得分:1)

将方法更改为GET,将dateType更改为json。查询字符串也需要q参数。

     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'
    });