今天我遇到了ElasticSearch和jQuery的問題。我尋找解決方案,但我找不到解決方案。使用jQuery/Ajax進行Elasticsearch查詢
我想從使用jQuery的ElasticSearch獲取一些數據。當我使用curl代替時,它正常工作:
curl -XGET "http://localhost:9200/locations/_search?pretty=true" -d '
{
"sort": [
"_score",
{
"_geo_distance": {
"location": {
"lat" : 40.715,
"lon": -73.998
},
"order": "asc",
"unit": "km",
"distance_type": "plane"
}
}
]
}'
但是當我使用jQuery時它不起作用。我試過了:
var data = {
"query": {
"filtered": {
"filter": {
"geo_distance": {
"distance": "1km",
"location": {
"lat" : 40.715,
"lon": -73.998
}
}
}
}
}
}
$.ajax({
method: "GET",
url: "http://localhost:9200/locations/_search?pretty=true",
crossDomain: true,
async: false,
data: data,
dataType : 'json',
contentType: 'application/json',
})
.done(function(data) {
console.log(data);
})
.fail(function(data) {
console.log(data);
});
我試圖用JSON.stringify(data)傳遞數據,但它也不起作用。我甚至嘗試將方法從「GET」更改爲「POST」,但沒有結果。那麼,它的工作。 ElasticSearch會返回包含某些位置的響應,但我的位置離我請求的位置很遠。 40.715,-73.998位置是紐約,當我使用curl它返回位置在紐約,但是當我使用jQuery我在墨西哥得到位置,所以我認爲我的「數據」變量被忽略。我提到我試圖使用json.Stringify。是的,但它返回錯誤:
Object { readyState: 0, getResponseHeader: .ajax/y.getResponseHeader(), getAllResponseHeaders: .ajax/y.getAllResponseHeaders(), setRequestHeader: .ajax/y.setRequestHeader(), overrideMimeType: .ajax/y.overrideMimeType(), statusCode: .ajax/y.statusCode(), abort: .ajax/y.abort(), state: .Deferred/e.state(), always: .Deferred/e.always(), catch: .Deferred/e.catch(),… }
那麼,如何使它工作?