Created
May 29, 2014 13:53
-
-
Save mgrigajtis/e8cc737ecf405b14bf24 to your computer and use it in GitHub Desktop.
Parsing ElasticSearch Results with Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedInputStream; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import org.json.JSONArray; | |
import org.json.JSONObject; | |
protected void foo () { | |
// The input stream from the JSON response | |
BufferedInputStream buffer = null; | |
// URL objects | |
String url = ""; | |
URL urlObject = null; | |
URLConnection con = null; | |
String response = ""; | |
// JSON objects | |
JSONArray hitsArray = null; | |
JSONObject hits = null; | |
JSONObject source = null; | |
JSONObject json = null; | |
try { | |
// get a JSON object from ElasticSearch | |
url = "http://10.49.236.132:9200/dfc/_search?q="; | |
// configure the URL request | |
urlObject = new URL(url); | |
con = urlObject.openConnection(); | |
con.setRequestProperty("User-Agent", "Mozilla/5.0"); | |
buffer = new BufferedInputStream(con.getInputStream()); | |
while (buffer.available()>0) { | |
response += (char)buffer.read(); | |
} | |
buffer.close(); | |
// parse the JSON response | |
json = new JSONObject(response); | |
hits = json.getJSONObject("hits"); | |
hitsArray = hits.getJSONArray("hits"); | |
for (int i=0; i<hitsArray.length(); i++) { | |
JSONObject h = hitsArray.getJSONObject(i); | |
source = h.getJSONObject("_source"); | |
//string object = (source.getString("the string you want to get")); | |
} | |
} catch(Exception e) { | |
// handle the exception | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment