2017-06-18 107 views
2

我正在使用彈性搜索的Ajax請求來獲取搜索結果。 最後,我找到了我必須去查詢的查詢。 (這是一個後續問題linkElasticsearch:cURL到Ajax請求

這裏是捲曲查詢:

[~]$ curl -XGET 'localhost:9200/firebase/_search?pretty' -H 'Content-Type: application/json' -d' 
> {"query": {"match": {"song": {"query": "i am in", "operator": "and"}}}}' 

結果:

{ 
    "took" : 286, 
    "timed_out" : false, 
    "_shards" : { 
    "total" : 5, 
    "successful" : 5, 
    "failed" : 0 
    }, 
    "hits" : { 
    "total" : 1, 
    "max_score" : 0.8630463, 
    "hits" : [ 
     { 
     "_index" : "firebase", 
     "_type" : "song", 
     "_id" : "0001", 
     "_score" : 0.8630463, 
     "_source" : { 
      "song" : "i am in california", 
      "song_name" : "hello", 
      "song_url" : "https://s3.ap-south-1.amazonaws.com/..." 
     } 
     } 
    ] 
    } 
} 

這個查詢使我產生正是我需要的。 當我通過AJAX使用相同的請求時,它給了我一個不好的請求。

Ajax.js

案例1:

$(function() { 
    $('#message').keyup(function() {  
     var query = { 
      "query": { 
       "match": { 
        "song": { 
         "query": $("#message").val(), 
         "operator": "and" 
        } 
       } 
      } 
     }; 

     console.log(JSON.stringify(query)); 

     $.ajax({ 
      type: "GET", 
      url: "http://localhost:9200/firebase/_search", 
      contentType: 'application/json', 
      data: query, 
      success: searchSuccess, 
      dataType: 'json' 
     }); 

    }); 

}); 

結果在控制檯:

enter image description here

案例2:如果我轉換「數據」透過JSON.stringify,它給了我:enter image description here

案例3:如果我改變了查詢結構如下和「數據使用JSON.stringify 「:

var query = { 
    query: { 
     match: { 
      song: { 
       query: $("#message").val(), 
       operator: "and" 
      } 
     } 
    } 
}; 

結果是:

enter image description here

我不是S在這裏有什麼問題,查詢是正確的,因爲使用相同的cURL我在bash中得到正確的結果。問題是如何在這裏正確創建Ajax請求。指針將不勝感激。

編輯:是的,我已經在elasticsearch.yml啓用CORS:

http.cors.enabled : true 
http.cors.allow-origin : "*" 
http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE 
http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length 

EDIT1:瀏覽器,網絡數據的下方,以提供更多的信息: enter image description here

EDIT2:完整的錯誤響應如下:

{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"request [/firebase/_search] contains unrecognized parameters: [query[match][song][operator]], [query[match][song][query]]"}],"type":"illegal_argument_exception","reason":"request [/firebase/_search] contains unrecognized parameters: [query[match][song][operator]], [query[match][song][query]]"},"status":400} 
+0

,而不是本地主機,你應該使用服務器的IP地址,其中elasticsearch安裝 –

+0

當我查詢的結構是簡單的 - 數據:{「Q」:$(「#消息」),VAL()}它工作正常亞歷克斯。本地主機沒有問題。但是由於普通的查詢並不能解決我的問題,所以我想使用匹配,因此發生了變化。因此,我不確定localhost是一個問題,雖然我會檢查並回來。 – Manganese

+0

不起作用。在9200上嘗試使用127.0.0.1(回送)和192.168.0.1(站點本地)。同樣的問題可以理解。另外,無論如何,我的elasticsearch現在都在本地運行。 – Manganese

回答

2

根據我的經驗,GET方法與身體的行爲有時很難預測。實際上,彈性搜索支持GET與身體,但我也有一些奇怪的結果取決於服務器,代理等配置...文檔甚至強調了JavaScript的問題(search with GET)。

通常情況下,使用POST代替GET有助於解決這些問題,或者至少有一個進一步的調試選項。

+0

該死的真棒是什麼!非常感謝,作品像魅力!並感謝文檔參考。 – Manganese