实践Neo4j之六索引

Index

index

manual index

1
2
3
4
5
6
7
8
9
10
String johnSmithName = "John Smith";
String johnSmithEmail = "jsmith@example.org";
Node personOne = graphDB.createNode();
personOne.setProperty("name", johnSmithName);
personOne.setProperty("email", johnSmithEmail);
IndexManager indexManager = graphDB.index();
//没有则创建索引,有则返回已存在的
Index<Node> userIndex = indexManager.forNodes("users");
//向索引添加数据
userIndex.add(personOne, "email", johnSmithEmail);
1
2
3
4
5
6
7
8
String userEmail = "jsmith@example.org";
//从索引中获取数据
IndexHits<Node> indexHits = userIndex.get("email", userEmail);
//单个
Node loggedOnUserNode = indexHits.getSingle();
if (loggedOnUserNode == null) {
	throw new NoSuchUserException("No user with email " + userEmail + " found");
}
1
2
3
4
5
IndexHits<Node> indexHits = userIndex.get("age", 34);
//多个
for (Node user : indexHits) {
	System.out.println(user.getProperty("name"));
}
1
2
//从索引中删除数据
userIndex.remove(loggedOnUserNode,"email", userEmail);

schema indexing

1
2
Label movieLabel = DynamicLabel.label("MOVIE");
graphDb.schema().indexFor(movieLabel).on("name").create();
1
ResourceIterable<Node> result = graphDb.findNodesByLabelAndProperty(movieLabel, "name", "Michael Collins");

auto-indexing

server mode

1
2
3
4
5
node_auto_indexing=true
relationship_auto_indexing=true

node_keys_indexable=name, dateOfBirth
relationship_keys_indexable=type,name

embedded

1
2
3
4
5
6
7
8
9
Map<String, String> config = new HashMap<String, String>();

config.put( Config.NODE_AUTO_INDEXING, "true" );
config.put( Config.RELATIONSHIP_AUTO_INDEXING, "true" );

config.put( Config.NODE_KEYS_INDEXABLE, "name, dateOfBirth" );
config.put( Config.RELATIONSHIP_KEYS_INDEXABLE, "type, name" );

EmbeddedGraphDatabase graphDb = new EmbeddedGraphDatabase("/var/neo4j/data", config );
1
2
3
AutoIndexer<Node> nodeAutoIndexer = graphDb.index().getNodeAutoIndexer();
IndexHits<Node> nodesWithMatchingName = nodeAutoIndexer.getAutoIndex().get("name", "John");
Node userNode = nodesWithMatchingName.getSingle();