Shivyesh Agnihotri
Shivyesh Agnihotri

Reputation: 11

elastic search query using curl in java

I have the following query which i am able to run through command line :

 curl -XPOST "http://35.160.73.241:9201/products/_search" -d 
                                  "{"query":{"match":{"campaign_id":"12239"}}}"

I need to run the above query using java. I am using the following code :

     try {
            Process process = Runtime.getRuntime().exec("curl -XPOST
                        \"http://35.160.73.241:9201/products/_search\" -d
                       \"{\"query\":{\"match\":{\"campaign_id\":\"12239\"}}}\"");
            int resultCode = process.waitFor();
            System.out.println(resultCode);
            if (resultCode == 0) {
                // all is good
            } 
        } catch (Exception ex) {
            // process cause
            ex.printStackTrace();
        }

But it is giving me the following exception :

java.io.IOException: Cannot run program "curl": CreateProcess 
                     error=2, The system cannot find the file specified

Please help me to run the query using Java.

Upvotes: 0

Views: 1948

Answers (3)

Munish Chouhan
Munish Chouhan

Reputation: 318

You can use QueryBuilders for query the elasticsearch. org.elasticsearch.index.query.QueryBuilders

Here are some examples: Java Code Examples for org.elasticsearch.index.query.QueryBuilders

Upvotes: 0

Monish Sen
Monish Sen

Reputation: 1888

Why dont you just use a java client for elastic search instead of using curl. There are distinct advantages, such as being able to construct queries easily and being aware of cluster state

Upvotes: 1

Titus
Titus

Reputation: 22474

You need to set the environment. Try this:

String env = new String[] { "PATH=/bin:/usr/bin/" };
String[] cmd = new String[] {"curl", "-XPOST", "\"http://35.160.73.241:9201/products/_search\"", "-d", "\"{\"query\":{\"match\":{\"campaign_id\":\"12239\"}}}\""}
Process process = Runtime.getRuntime().exec(cmd, env);

This will work if you're using a Linux system.

A better solution will be to use HttpURLConnection. Which is the usual way of creating HTTP connections and it's system independent.

Upvotes: 0

Related Questions