ElasticSearch queries to its REST API - Segolene-Albouy/Memoire-TNAH2019 GitHub Wiki

HTTP requests to Elasticsearch

Cross origin requests

If you are performing ajax calls on your localhost, you must allow elasticsearch to manage cross origin requests : in order to do that, the config file (to access when you are in the etc directory, run the command sudo vim elasticsearch/elasticsearch.yml) must contain the settings below (more on settings here) :

http.cors.enabled: true
# to specify origins that are allowed ("/" being treated as regular expression)
http.cors.allow-origin: /https?:\/\/localhost(:[0-9]+)?/
http.cors.allow-credentials: true

Simple GET query

The ajax request must look like (you can use the parameters listed here) :

var query = {
            q: 'id:5'
        };
var entity = "work";

$.ajax({
    url: `http://localhost:9200/${entity}/_search`,
    xhrFields: {
        withCredentials: true
    },
    data: query,
    success: function(data) {
        // your code there
    }
});

Query as JSON string

If you want to use a query formatted in JSON (as the ones used in the kibana interface), you should use this kind of syntax :

var query = '{"query":{"match":{"id":"5"}}}';
var entity = "work";

$.ajax({
    url: `http://localhost:9200/${entity}/_search?
          source_content_type=application/json&source=${query}`,
    xhrFields: {
        withCredentials: true
    },
    success: function(data) {
        // your code there
    }
});