Java API for Graph

Hi Sharad,
Below is a demo which obviously depends on core elasticsearch resources and the jar from the xpack plugin for graph:

package org.elasticsearch;

import java.net.InetAddress;
import java.util.Collection;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.graph.GraphPlugin;
import org.elasticsearch.graph.action.GraphExploreAction;
import org.elasticsearch.graph.action.GraphExploreRequestBuilder;
import org.elasticsearch.graph.action.GraphExploreResponse;
import org.elasticsearch.graph.action.Hop;
import org.elasticsearch.graph.action.Vertex;
import org.elasticsearch.index.query.QueryBuilders;

/**
 * Demo graph client - find elastic meetup attendees and what other meetup groups they frequent
 */
public class GraphDemoClient {

	public static void main(String[] args) throws Exception {
	
		TransportClient client = TransportClient.builder()
				.settings(Settings.builder()
					.put("cluster.name", "elasticsearch")			    
					.build())
				.addPlugin(GraphPlugin.class)
				.build()
				.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

	
		int requiredNumberOfSightings=1;
	
		GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client, GraphExploreAction.INSTANCE).setIndices("meetuprsvps");
		Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("_all", "elasticsearch"));
		// elasticsearch meetup attendees
		hop1.addVertexRequest("member_id").size(10).minDocCount(requiredNumberOfSightings); 
		// groups attended by elastic attendees
		grb.createNextHop(null).addVertexRequest("group_id").size(10).minDocCount(requiredNumberOfSightings); 
	
		GraphExploreResponse response = grb.get();
		Collection<Vertex> vertices = response.getVertices();
	
		System.out.println("==Members===");
		for (Vertex vertex : vertices) {
			if(vertex.getField().equals("member_id")){
				System.out.println(vertex.getTerm());        		
			}
		}
	
		System.out.println("==Groups===");
		for (Vertex vertex : vertices) {
			if(vertex.getField().equals("group_id")){
				System.out.println(vertex.getTerm());        		
			}
		}        

		client.close();

	}

}
1 Like