javascript 使用 Elasticsearch 搜索进行 AJAX 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13144794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:56:01  来源:igfitidea点击:

AJAX Call with Elasticsearch Search

javascriptjqueryajaxcouchdbelasticsearch

提问by neurosnap

I've been trying to figure out how to correctly request data from elasticsearch using a jQuery AJAX call. I either get an parsing error or I'll get every document in the index I'm searching under.

我一直在试图弄清楚如何使用 jQuery AJAX 调用正确地从 elasticsearch 请求数据。我要么得到解析错误,要么得到我正在搜索的索引中的每个文档。

    $(document).ready(function() {

    var timer = null;
    function dicom_search() {
        var box = $('#s_box').val();

        $.ajax({
            url: 'http://localhost:9200/dicoms/dicoms/_search',
            type: 'POST',
            //contentType: 'application/json; charset=UTF-8',
            crossDomain: true,
            dataType: 'json',
            data: {
                query:{match:{_all:$('#s_box').val()}},
                pretty: true,
                fields: '_id'
            },
            success: function(response) {
                var data = response.hits.hits;
                var doc_ids = [];
                var source = null;
                var content = '';

                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        source = data[i].fields;
                        doc_ids.push(source._id);
                        content = content + ' ' + source._id + '<br />';
                    }

                    $('#res').removeClass('text-error').addClass('text-success').html(content);
                } else {
                    $('#res').removeClass('text-success').addClass('text-error').html('No results found.');
                }


            }
        });
    }

    $('#s_box').live('keyup', function() {

        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(dicom_search, 600);

    });
});

Here is my error:

这是我的错误:

{
   "error":"SearchPhaseExecutionException[Failed to execute phase [query], total failure; shardFailures {[GUiivW0TQVSNv2HQyxu8Vw][dicoms][0]: SearchParseException[[dicoms][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [_na_]]]; nested: ElasticSearchParseException[Failed to derive xcontent from org.elasticsearch.common.bytes.ChannelBufferBytesReference@779479bb]; }{[GUiivW0TQVSNv2HQyxu8Vw][dicoms][3]: SearchParseException[[dicoms][3]: from[-1],size[-1]: Parse Failure [Failed to parse source [_na_]]]; nested: ElasticSearchParseException[Failed to derive xcontent from org.elasticsearch.common.bytes.ChannelBufferBytesReference@779479bb]; }{[GUiivW0TQVSNv2HQyxu8Vw][dicoms][1]: SearchParseException[[dicoms][1]: from[-1],size[-1]: Parse Failure [Failed to parse source [_na_]]]; nested: ElasticSearchParseException[Failed to derive xcontent from org.elasticsearch.common.bytes.ChannelBufferBytesReference@779479bb]; }{[GUiivW0TQVSNv2HQyxu8Vw][dicoms][4]: SearchParseException[[dicoms][4]: from[-1],size[-1]: Parse Failure [Failed to parse source [_na_]]]; nested: ElasticSearchParseException[Failed to derive xcontent from org.elasticsearch.common.bytes.ChannelBufferBytesReference@779479bb]; }{[GUiivW0TQVSNv2HQyxu8Vw][dicoms][2]: SearchParseException[[dicoms][2]: from[-1],size[-1]: Parse Failure [Failed to parse source [_na_]]]; nested: ElasticSearchParseException[Failed to derive xcontent from org.elasticsearch.common.bytes.ChannelBufferBytesReference@779479bb]; }]",
   "status":500
}

EDIT: I figured it out:

编辑:我想通了:

var data = {
            query: {
                match: {
                    _all: $('#s_box').val()
                }
            },
            fields: '_id'
        }; 

$.ajax({
            url: 'http://localhost:9200/dicoms/dicoms/_search',
            type: 'POST',
            //contentType: 'application/json; charset=UTF-8',
            crossDomain: true,
            dataType: 'json',
            data: JSON.stringify(data),
            success: function(response) {
                var data = response.hits.hits;
                var doc_ids = [];
                var source = null;
                var content = '';

                if (data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        source = data[i].fields;
                        doc_ids.push(source._id);
                        content = content + ' ' + source._id + '<br />';
                    }

                    $('#res').removeClass('text-error').addClass('text-success').html(content);
                } else {
                    $('#res').removeClass('text-success').addClass('text-error').html('No results found.');
                }


            },
            error: function(jqXHR, textStatus, errorThrown) {
                var jso = jQuery.parseJSON(jqXHR.responseText);
                error_note('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --<br />' + jso.error);
            }
        });

回答by dadoonet

You can have a look here: https://github.com/dadoonet/devoxxfr_demo/blob/gh-pages/index.html#L512

你可以看看这里:https: //github.com/dadoonet/devoxxfr_demo/blob/gh-pages/index.html#L512

It could help you to solve your issue.

它可以帮助您解决您的问题。

回答by sujaypatil

Instead of writing your AJAX call, I'd suggest you use this tool called Postman. Postman has a simple motto -

我建议您使用名为Postman 的工具,而不是编写您的 AJAX 调用。邮递员有一个简单的座右铭——

Making API development easy

让 API 开发变得简单

So in case you have trouble writing your ES requests, or maybe you decide not to use jQuery AJAX/XHR, and maybe you'd like to use cURL/Unirest/NSURL and what not, you can just use the Postman request builder to write down your simple Http Request, then you'll find a link called codein the box right below that, and you can generate requests in the language of your choice using that. Including AJAX, yes. So I'd recommend you try using that.

因此,如果您在编写 ES 请求时遇到问题,或者您决定不使用 jQuery AJAX/XHR,或者您想使用 cURL/Unirest/NSURL 等等,您可以使用 Postman 请求构建器来编写在您的简单 Http 请求中,您会在其下方的框中找到一个名为code的链接,您可以使用它以您选择的语言生成请求。包括 AJAX,是的。所以我建议你尝试使用它。

Here's the link where you can download Postman from - https://www.getpostman.com/postman

这是您可以从以下位置下载 Postman 的链接 - https://www.getpostman.com/postman