Implementing an efficient MapReduce algorithm for counting triangles in a very large graph involves several steps. Below, I'll provide a comprehensive guide, including Java code for Hadoop MapReduce, input format, and commands to execute the program. This implementation is inspired by efficient triangle-counting algorithms commonly found in research literature.
Overview of the Algorithm
Counting triangles in a graph using MapReduce typically involves the following steps:
- Preprocessing: Ensure the graph is undirected and remove duplicate edges.
- Adjacency List Construction: Create adjacency lists for each vertex.
- Edge Pair Generation: Generate all possible pairs of edges that could form a triangle.
- Triangle Identification: Identify and count valid triangles by checking the existence of the third edge.
This process often requires multiple MapReduce jobs. In this implementation, we'll use two MapReduce jobs:
- Job 1: Construct adjacency lists.
- Job 2: Generate potential triangles and count the actual triangles.
Input Format
The input graph should be provided as a text file where each line represents an undirected edge between two vertices, separated by a tab. For example:
A B
A C
B C
B D
C D
This represents a graph with edges: A-B, A-C, B-C, B-D, and C-D.
Hadoop Setup Requirements
- Hadoop installed and properly configured.
- Java Development Kit (JDK) installed.
- Maven or another build tool (optional but recommended for managing dependencies).
Implementation
1. Job 1: Adjacency List Construction
This job reads the edge list and constructs an adjacency list for each vertex.
AdjacencyListMapper.java
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class AdjacencyListMapper extends Mapper<Object, Text, Text, Text> {
private Text vertex = new Text();
private Text neighbor = new Text();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// Input line format: vertex1 \t vertex2
String[] vertices = value.toString().split("\t");
if (vertices.length == 2) {
String vertex1 = vertices[0];
String vertex2 = vertices[1];
vertex.set(vertex1);
neighbor.set(vertex2);
context.write(vertex, neighbor);
vertex.set(vertex2);
neighbor.set(vertex1);
context.write(vertex, neighbor);
}
}
}
AdjacencyListReducer.java
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class AdjacencyListReducer extends Reducer<Text, Text, Text, Text> {
private Text adjacencyList = new Text();
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
StringBuilder sb = new StringBuilder();
for (Text val : values) {
sb.append(val.toString()).append(",");
}
// Remove trailing comma
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
adjacencyList.set(sb.toString());
context.write(key, adjacencyList);
}
}
2. Job 2: Triangle Counting
This job uses the adjacency lists to generate potential triangles and counts the actual triangles.
TriangleCountMapper.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class TriangleCountMapper extends Mapper<Object, Text, Text, Text> {
private Text vertexPair = new Text();
private Text vertex = new Text();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
// Input line format: vertex \t neighbor1,neighbor2,...
String[] parts = value.toString().split("\t");
if (parts.length == 2) {
String vertexId = parts[0];
String[] neighbors = parts[1].split(",");
List<String> neighborList = new ArrayList<>();
for (String neighbor : neighbors) {
if (vertexId.compareTo(neighbor) < 0) { // Ensure ordering to avoid duplicates
neighborList.add(neighbor);
}
}
// Emit all possible pairs of neighbors
for (int i = 0; i < neighborList.size(); i++) {
for (int j = i + 1; j < neighborList.size(); j++) {
String neighbor1 = neighborList.get(i);
String neighbor2 = neighborList.get(j);
vertexPair.set(neighbor1 + "," + neighbor2);
vertex.set(vertexId);
context.write(vertexPair, vertex);
}
}
}
}
}
TriangleCountReducer.java
import java.io.IOException;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class TriangleCountReducer extends Reducer<Text, Text, Text, Text> {
private Text result = new Text();
private static long triangleCount = 0;
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
// key: neighbor1,neighbor2
// values: list of vertexIds that have both neighbor1 and neighbor2
int count = 0;
for (Text val : values) {
count++;
}
// Each value represents a triangle
triangleCount += count;
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
result.set(String.valueOf(triangleCount));
context.write(new Text("Total Triangles"), result);
}
}
3. Driver Class
This class sets up and runs the two MapReduce jobs in sequence.
TriangleCountDriver.java
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class TriangleCountDriver {
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: TriangleCountDriver <input path> <temp output path> <final output path>");
System.exit(-1);
}
Configuration conf = new Configuration();
// Job 1: Adjacency List Construction
Job job1 = Job.getInstance(conf, "Adjacency List Construction");
job1.setJarByClass(TriangleCountDriver.class);
job1.setMapperClass(AdjacencyListMapper.class);
job1.setReducerClass(AdjacencyListReducer.class);
job1.setOutputKeyClass(Text.class);
job1.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job1, new Path(args[0]));
FileOutputFormat.setOutputPath(job1, new Path(args[1]));
boolean success = job1.waitForCompletion(true);
if (!success) {
System.exit(1);
}
// Job 2: Triangle Counting
Job job2 = Job.getInstance(conf, "Triangle Counting");
job2.setJarByClass(TriangleCountDriver.class);
job2.setMapperClass(TriangleCountMapper.class);
job2.setReducerClass(TriangleCountReducer.class);
job2.setOutputKeyClass(Text.class);
job2.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job2, new Path(args[1]));
FileOutputFormat.setOutputPath(job2, new Path(args[2]));
success = job2.waitForCompletion(true);
System.exit(success ? 0 : 1);
}
}
Compilation and Packaging
To compile and package the Hadoop MapReduce program, follow these steps:
- Create a Directory Structure:
TriangleCount/
├── src/
│ └── main/
│ └── java/
│ └── TriangleCountDriver.java
│ └── AdjacencyListMapper.java
│ └── AdjacencyListReducer.java
│ └── TriangleCountMapper.java
│ └── TriangleCountReducer.java
├── pom.xml
- Create a
pom.xml File (if using Maven):
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>trianglecount</artifactId>
<version>1.0</version>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>TriangleCountDriver</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Hadoop dependencies -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
</project>
- Compile and Package:
Navigate to the TriangleCount directory and run:
mvn clean package
This command will generate a JAR file with all dependencies, typically located at target/trianglecount-1.0-jar-with-dependencies.jar.
Execution
Assuming you have Hadoop installed and running, follow these steps to execute the program:
- Prepare Input Data:
Create an input file (e.g., input_graph.txt) with the edge list as described earlier.
A B
A C
B C
B D
C D
- Upload Input to HDFS:
hdfs dfs -mkdir /user/hadoop/trianglecount/input
hdfs dfs -put input_graph.txt /user/hadoop/trianglecount/input/
- Run the MapReduce Job:
hadoop jar target/trianglecount-1.0-jar-with-dependencies.jar TriangleCountDriver /user/hadoop/trianglecount/input/ /user/hadoop/trianglecount/temp_output/ /user/hadoop/trianglecount/final_output/
Here:
/user/hadoop/trianglecount/input/: Input path in HDFS.
/user/hadoop/trianglecount/temp_output/: Temporary output path for Job 1.
/user/hadoop/trianglecount/final_output/: Final output path for Job 2.
- View the Result:
After the job completes, retrieve and view the triangle count.
hdfs dfs -cat /user/hadoop/trianglecount/final_output/part-r-00000
Expected output:
Total Triangles 2
This indicates that there are 2 triangles in the input graph:
- Triangle involving A-B-C
- Triangle involving B-C-D
Notes and Optimizations
- Edge Ordering: Ensuring that for each edge (u, v),
u < v can help reduce duplicate processing and streamline the pairing process.
- Partitioning: Proper partitioning of data can enhance performance by balancing the load across reducers.
- Combiner Usage: Implementing a combiner can reduce the amount of data shuffled between mappers and reducers.
- Scalability: This implementation is a basic version. For very large graphs, consider optimizations such as edge partitioning, neighbor list compression, and using more advanced data structures.
Conclusion
This implementation provides a basic yet efficient way to count triangles in a large graph using Hadoop MapReduce in Java. Depending on your specific requirements and the size of the graph, further optimizations and refinements may be necessary to enhance performance and scalability.