Understanding Graph Selections

Understanding graph selections is critical to using the Thinkmap API. Fundamentally, a graph selection represents a sub-set of entities in a graph.

Most of the time, you obtain a graph selection by calling the select() method on a thinkmap.graph.Graph object.

For example, let's say you have a graph called mygraph. To select all the entities in the graph (nodes & edges), you call the select method with no arguments:

var mygraph = new thinkmap.graph.Graph();
// select all entities in mygraph
var allEntities = mygraph.select();

A selection is inherently and forever tied to the graph from which it was selected. To get the graph associated with a selection, just call the graph() method on the selection.

mygraph.select().graph() // returns mygraph

To select all the entities of a particular type in a graph, you can call the graph.select() method and pass a string.

var allNodes = mygraph.select('node');
var allEntities = mygraph.select('entity'); // same as select()
// If you have custom entity types defined, you can select those too.
var justMovies = mygraph.select('movie');

You can pass much more than strings to the select method. Here's a brief summary of the arguments you can pass to the graph.select() method:

Argument Type Description
string Selects all entities of that type. Selections by type use internal indexes that the thinkmap API maintains and are extremely fast.
JSON Object Uses a JSON object as a query condition and tests every entity in the graph against the given condition. See below for the format of conditions. Selections by condition may be optimized by creating indexes using the graph.createIndex() method.
Array.<thinkmap.graph.Entity> Returns a selection containing just the entities in the array (if they are contained in the graph).
thinkmap.graph.Entity Returns a selection containing just that entity, if it is contained in the graph, otherwise an empty selection.
thinkmap.graph.Selection Returns a selection (associated with this graph) that contains all the entities in this graph that are ALSO in the given selection. Typically, the selection passed in is from a different graph.
function( this:thinkmap.graph.Entity, Object ) : boolean Tests every entity in the graph against the given function, using each entity as the this pointer and passing the value of entity.data as the first argument. If the function returns true, the entity is included in the selection. Note that creating selections by function can be fairly resource-intensive on large graphs.

Using JSON Objects to create a Selection

One of the most powerful ways to create selections is to use a JSON object as a query parameter. Let's look at some of the things you can do:

	// Use the "$search" operator to do a full text search for entities that
	// have a string property that contains the word "meeting".
	var meetings = mygraph.select({$search:'meeting'});
	
	// select entities that have a lastname property equal to 'smith'
	var smiths = mygraph.select({lastname:'smith'});
	
	// the above, but limited to nodes only, using the $t type operator
	var nodes = mygraph.select({$t:'node',lastname:'smith'});
	
	// select people making over $100,000 dollars
	var highEarners = mygraph.select({$t:'person',salary:{$gt:100000}});		

Using Functions to create a Selection

If you cannot express your selection criteria using a JSON object, you may have to use a function. Be aware however, that using a function will require testing your function against every entity in the graph, which may be resource intensive.

Here's an example:

// profit margin greater than 20%
mygraph.select(function(data){ 
   return ((data.price - data.cost) / data.price > .2); 
});

// note that you can combine JSON conditions and functions to get better
// performance - here we add the criteria to test only nodes, in addition
// to our custom function criteria, which we specify using the '$fn'
// operator.
mygraph.select({$t:'node', $fn:function(data){ 
  return ((data.price - data.cost) / data.price > .2); 
}});

Selection Limitations

The advantage of Selections is that they allow you to work with the graph using a synchronous API. However, Selections can only deal with data that has already been loaded into the graph. Because of their synchronous nature, they can not fetch data from an underlying datasource or traverse multi-step paths through a graph. To do this, you must use the Thinkmap Query API, which allows you to create complex multi-step graph queries that execute asnychronously and can load data into a graph from a remote datasource on-demand.

Selection Set Logic

Selections can be composed using set logic using the union, intersection, difference, and complement methods.

	var actors    = mygraph.select('actor');
	var actresses = mygraph.select('actress');
	
	// union the two selections to form a new selection
	var both  = actors.union(actresses);
	
	// all entities with a last name of smith
	var smiths = mygraph.select({lastname:'smith'});
	
	// only actors & actresses with a lastname of 'smith' 
	var intersect = smiths.intersection(both);
	
	// actors and actresses that do NOT have a lastname of 'smith'
	var notsmith = both.difference( smiths );
	
	// entities with a last name of smith that are not actors or actresses
	var smithsNotActorsActress = both.complement(smith);

Subselections

Any argument you can pass to graph.select() can also be used to create a sub-selection.

// select using sub-selection
var actorsNamedSmith = mygraph.select('actor').select({'lastname':'smith'});

// is the same as this (select using intersection)
var actorsNamedSmith = mygraph.select('actor')
						.intersection(mygraph.select({'lastname':'smith'}));

// is equivlent to this (this is the fastest way to do it)
var actorsNamedSmith = mygraph.select({$t:'actor','lastname':'smith'});

Operations on Selections

There are many operations you can perform on a selection. Let's take a look at some basic operations:

	// get the number of entities in a selection
	var actorCount = mygraph.select('actor').count();
	
	// convert a selection to an array
	var actors = mygraph.select('actor').toArray();

	// get the first actor in a selection
	var anyActor = mygraph.select('actor').first();

	// call a function for each entity in a selection
	mygraph.select('actor').forEach(function(e) {
		console.log(e.data.lastname);	
	});

Here are some more complex operations you can do with a selection:

	// remove all actors from the graph
	mygraph.select('actor').remove();
	
	// increment employees salaries and tell the graph the given entities
	// have had updates applied to their data (update indexes, etc.)
	mygraph.select('employee')
	       .forEach(function(e) { e.data.salary += 1000; })
	       .dataUpdate();
	
	// create a retention policy that prevents actresses from being removed 
	// from the graph
	mygraph.select('actress').retainFor(function(e) { return true; });

Display Selections

When you obtain a selection from a thinkmap.display.Display it returns a thinkmap.display.Selection, which is subclass of thinkmap.graph.Selection. Display Selections add some additional methods that allow you to operate on entities as a group in that display. Let's look at some of those methods:

	// prevent all actors from moving in the display
	var frozenActors = mydisplay.select('actor').freeze();
	
	// and release them
	frozenActors.release();
		
	// put all actors at a random x,y position 
	mydisplay.select('actor').position(function(e) {
		return { x: Math.random() * 100, y : Math.random() * 100 };
	});
	
	// move all actors 10 pixels to the right
	mydisplay.select('actor').drag(10,0);		

Transitioning Display Selections

If you would like to animate the operations above instead of performing them immediately, you can call the DisplaySelection.transition() method and obtain a TransitionedDisplaySelection. Here's an example:

		
	// animate all nodes to a random x,y position 
	mydisplay.select('node').transition().position(function(e) {
		return { x: Math.random() * 100, y : Math.random() * 100 };
	});

Wrapping Up

As you can see, there's a lot you can do with graph selection. To learn more about the graph selection API, you can view the full API documentation, which is available by clicking one of the links below: