简体   繁体   中英

How to import Elasticsearch data(JSON) into Google Charts?

I try to use Elasticsearch data to create a table with Google Charts. I followed this solution: Populate Google Chart with Search Data from Elasticsearch

But I cannot see any data or graph displayed. I think it is because I don't transfer data correctly. Could anyone tell me the problem of the following code?

     <html>
      <head>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> 
        </script>
        <script type="text/javascript">
      google.load('visualization', {'packages':['table']});
      google.setOnLoadCallback(drawTable);

      function drawTable() {
      var json;
      $.ajax({
           url: 'http://localhost:9200/people/man/_search',
        type: 'POST',
        data :
            JSON.stringify(
                {
                    "query" : { "match_all" : {} }
                }),
        dataType : 'json',
        async: false,
        success: function(data){
            json = data;
        }
    })



  var jdata = {};
  jdata.cols = [
{
    "id": "",
    "label": "name",
    "type": "string"
},
{
    "id": "",
    "label": "country",
    "type":"string"
}
 ];

   jdata.rows = [
{
    "c": [
        {
            "v": json.hits.hits[0]._source.name
        },
        {
            "v": json.hits.hits[0]._source.country
        }
    ]
}
];

   var data = new google.visualization.DataTable(jdata);

   var table = new google.visualization.Table(document.getElementById('table_div'));
 table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
 </script>
</head>

<body>
     <div id="table_div"> </div>
</body>
</html>

I find three problems of showing nothing in this code. No big error but good details to notice.

  1. add header "Content-Type", "application/json". I used "xmlhttp.setRequestHeader("Content-Type", "application/json");"
  2. 'json' is defined in a function. If using json outside the function, it gives blank file back.(small error, but quite annoying if you don't notice this)
  3. don't forget to transfer string to json with "var json = JSON.parse(json);"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM