2016-07-12 96 views
0

今天我遇到了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(),… } 

那麼,如何使它工作?

回答

0

好的,問題已解決。我的代碼沒問題。我將方法更改爲「POST」。使用Google Chrome開發者工具我注意到代碼的其他部分不好。在我的代碼

"location": { 
    "lat" : 40.715, 
    "lon": -73.998 
} 

緯度和經度是一個變量(我把它們改成COORDS爲StackOverflow的問題)wchich是空的,因爲我的代碼的另一部分不能分配從getCurrentPosition(新值)(默認值爲0,這就是爲什麼我的代碼不工作)。所以,代碼的正確版本是:

var data = { 
    "query": { 
    "filtered": { 
     "filter": { 
     "geo_distance": { 
      "distance": "1km", 
      "location": { 
      "lat" : lat, 
      "lon": lon 
      } 
     } 
     } 
    } 
    } 
} 

$.ajax({ 
    method: "GET", 
    url: "http://localhost:9200/locations/_search?pretty=true", 
    crossDomain: true, 
    async: false, 
    data: JSON.stringify(data), 
    dataType : 'json', 
    contentType: 'application/json', 
}) 
.done(function(data) { 
    console.log(data); 
}) 
.fail(function(data) { 
    console.log(data); 
}); 

注意緯度和經度都是需要的參數是一個GeoPoint

變量