来自弹性搜索过滤查询的Ajax 400错误请求

时间:2017-10-15 20:03:24

标签: json ajax elasticsearch get bad-request

当查询有过滤器时,我想使用Ajax从elasticsearch检索数据。 我正在使用GET。

我的代码如下:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
    $(document).ready(function(){
        $.ajax({
            type: 'GET',
            url : 'HOST/tomo2o/shop/_search',
            crossDomain: true,
            data: JSON.stringify({"query":{"match":{"catlev1":"Motors"}}}),
            contentType:'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                console.log(data);
            },
            error: function(e) {
                console.log(e);
            }
        });
    });
</script>

我做了人们建议做的3件事:

  1. 字符串化json过滤器
  2. 将数据类型设置为json
  3. 将内容类型设置为application / json
  4. 但我仍然收到以下错误:

    GET HOST/tomo2o/shop/_search?{%22query%22:{%22match%22:{%22catlev1%22:%22Motors%22}}} 400 (Bad Request)
    

1 个答案:

答案 0 :(得分:2)

如果您想传递DSL query in the query string,则需要在source参数中传递它,并添加source_content_type参数以指明内容类型

所以你可以这样做:

    $.ajax({
        type: 'GET',
        url : 'HOST/tomo2o/shop/_search',
        crossDomain: true,
        data: {
           source: JSON.stringify({"query":{"match":{"catlev1":"Motors"}}}),
           source_content_type: "application/json"
        },
        contentType:'application/json; charset=utf-8',
        dataType: 'json',
        success: function(data) {
            console.log(data);
        },
        error: function(e) {
            console.log(e);
        }
    });