woshitom
woshitom

Reputation: 5131

Ajax 400 bad request from an elastic search filtered query

I want to use Ajax to retrieve data from elasticsearch when the query has a filter. I'm using GET.

My code is the following:

<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>

I did the 3 things people suggest to do:

  1. stringify the json filter
  2. set the data type as json
  3. set the content type as application/json

But I'm still getting the following error:

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

Upvotes: 0

Views: 1232

Answers (1)

Val
Val

Reputation: 217474

When you want to pass a DSL query in the query string you need to pass it in the source parameter and also add a source_content_type parameter to indicate the content type

So you can do it like this:

    $.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);
        }
    });

Upvotes: 2

Related Questions