Export all ElasticSearch data to JSON file - exception

I need t export all data in the ElasticSearch and reindex all those data.
The export Java code as follows.
SearchResponse response = client.prepareSearch("news")
.setTypes("news_data")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(1000)
.setScroll(new TimeValue(600000))
.setSearchType(SearchType.SCAN)
.execute().actionGet();
String scrollid = response.getScrollId();
try {
//把导出的结果以JSON的格式写到文件里
BufferedWriter out = new BufferedWriter(new FileWriter("es", true));
while (true) {
SearchResponse response2 = client.prepareSearchScroll(scrollid)
.setScroll(new TimeValue(1000000))
.execute().actionGet();
SearchHits searchHit = response2.getHits();
//再次查询不到数据时跳出循环
if (searchHit.getHits().length == 0) {
break;
}
System.out.println("查询数量 :" + searchHit.getHits().length);
for (int i = 0; i < searchHit.getHits().length; i++) {
String json = searchHit.getHits()[i].getSourceAsString();
out.write(json);
out.write("\r\n");
}
}
System.out.println("查询结束");
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The numbers of documents is about 140W. Use this java code 60W documents can be exported and throw an exception.
远程主机强迫关闭了一个现有的连接

You have to use the scrollid from the previous response for your next request.
See https://www.elastic.co/guide/en/elasticsearch/reference/1.7/search-request-scroll.html#scroll-scan for more details
Perhaps you can try something like this instead?
SearchResponse response = client.prepareSearch("news")
.setTypes("news_data")
.setQuery(QueryBuilders.matchAllQuery())
.setSize(1000)
.setScroll(new TimeValue(600000))
.setSearchType(SearchType.SCAN)
.execute().actionGet();
int sequence = 0;
do
{
response = client.prepareSearchScroll(response.getScrollId())
.setScroll(new TimeValue(600000))
.execute().actionGet();
if (response.getHits().getHits().length > 0)
{
try
{
final BufferedWriter out = new BufferedWriter(new FileWriter("es-" + (++sequence) , true));
for (final SearchHit hit : response.getHits().getHits())
{
out.write(hit.getSourceAsString());
out.write("\r\n");
}
out.close();
}
catch (final IOException e)
{
e.printStackTrace();
}
}
}
while (response.getHits().hits().length > 0);

Related

Json Parse Failed- javafx

I am writing javafx app
I try to sava and load data using JSON
#FXML
private void OpenEvent(ActionEvent event) throws IOException, ParseException, Exception {
String jsonString = new String();
FileReader fileReader = new FileReader("test.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println("Check open event here");
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString += inputLine;
}
bufferedReader.close();
System.out.println(jsonString);
//GOOD HERE
JSONArray jlist;
try {
jlist = parseJsonArray(jsonString);
} catch (Exception ex) {
throw ex;
}
for (Object e : jlist) {
try {
JSONObject jentryParsed = (JSONObject) e;
LocalEvent entry = new LocalEvent();
entry.initFromJsonString(jentryParsed.toJSONString());
} catch (Exception ex) {
throw ex;
}
}
}
public JSONArray parseJsonArray(String jsonString) throws Exception {
JSONArray jlist;
JSONParser parser = new JSONParser();
System.out.println("Check parse here");
System.out.println(jsonString);
try {
jlist = (JSONArray) parser.parse(jsonString);
} catch (Exception ex) {
throw ex;
}
System.out.println("parsed finished");
if (jlist == null) {
System.out.println("jlist is null");
return null;
} else {
return jlist;
}
}
and here is my JSON file
[{"Description":"11111","Name":"11111","Datetime":2016-04-27},{"Description":"2222","Name":"2222","Datetime":2016-04-14}]
error:
Caused by: Unexpected token VALUE(-4) at position 54.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at todolist.MainController.parseJsonArray(MainController.java:276)
at todolist.MainController.OpenEvent(MainController.java:250)
... 50 more
It seems the json parse is failed.
is here anything wrong with my JSON file?
Thanks!!!!!!!
or the parse cannot recognize "-" in the datetime??

Converting finalBufferData into img url to display

I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.

Getting JSON Exception no value for?

I am trying to handle the json response, that is like
{"Status":true,"UserId":111,"FirstName":"dev","LastName":"dev","Gender":-1,"BirthdayDate":"0000-00-00","Phone":"","ProfilePicture":"","ProfilePicture60px":"","ProfilePicture120px":"","CountryId":-1,"Email":"droidwithmxxmail.com","Password":"******123","RegisterDate":"2015-05-08 20:08:07","SessionId":"fce248fe6499b7a9338a1b64554509eb77841"}
but getting org.json.JSONException: no value for exception
My code is this.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
allres =jsonObj.getJSONArray(jsonStr);
for (int i = 0; i < allres.length(); i++) {
JSONObject c = allres.getJSONObject(i);
userId = c.getString("UserId");
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this code:
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
userId = jsonObj.getString("UserId");
} catch (JSONException e) {
e.printStackTrace();
}
Your JSON string doesn't have an array in it, so the object that you will be getting from the first JSONObject is already where your information lives.

Blackberry how to get Json Response (java)

I want to get a JSON response on the simulator. How can I read JSON from the server?
public void run()
{
HttpConnection httpConn;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://example.com/login.php");
if (connDesc != null)
{
try {
httpConn = (HttpConnection)connDesc.getConnection();
final int iResponseCode = httpConn.getResponseCode();
Dialog.alert("Type: "+httpConn.getType());
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " + Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
HttpConnection connection = (HttpConnection)Connector.open(urlConection);
InputStream inputStream = connection.openInputStream();
if(connection.getResponseCode() == HttpConnection.HTTP_OK){
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
int readCharacter;
StringBuffer responseBuffer = new StringBuffer();
while ((readCharacter = reader.read()) != -1) {
responseBuffer.append((char) readCharacter);
connection.close();
inputStream.close();
reader.close();
String responseMessage = new String(responseBuffer);
}
}
You need to create JSONObject for the response.
try {
JSONObject object = new JSONObject(responseMessage);
} catch (JSONException e) {
e.printStackTrace();
}

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help