/** Node labels. */ public static class Labels { public static final Label WALLET = DynamicLabel.label("Wallet"); public static final Label OWNER = DynamicLabel.label("Owner"); public static final Label ADDRESS = DynamicLabel.label("Address"); public static final Label TRANSACTION = DynamicLabel.label("Transaction"); }
public void testModifyType() { final Set<Label> labelsBefore = new LinkedHashSet<>(); final Set<Label> labelsAfter = new LinkedHashSet<>(); String id = null; labelsBefore.add(DynamicLabel.label(AccessControllable.class.getSimpleName())); labelsBefore.add(DynamicLabel.label(TestFour.class.getSimpleName())); labelsAfter.add(DynamicLabel.label(AccessControllable.class.getSimpleName())); labelsAfter.add(DynamicLabel.label(TestFive.class.getSimpleName())); // create a new node, check labels, modify type, check labels again try (final Tx tx = app.tx()) { // create entity of type TestFour final TestFour testEntity = createTestNode(TestFour.class); // check if node exists assertNotNull(testEntity); // check labels before type change assertTrue(labelsBefore.containsAll(Iterables.toSet(testEntity.getNode().getLabels()))); // save ID for later use id = testEntity.getUuid(); // change type to TestFive testEntity.setProperty(GraphObject.type, TestFive.class.getSimpleName()); // commit transaction tx.success(); } catch (FrameworkException fex) { fail("Unexpected exception"); } try (final Tx tx = app.tx()) { final TestFive testEntity = app.get(TestFive.class, id); assertNotNull(testEntity); // check labels after type change assertTrue(labelsAfter.containsAll(Iterables.toSet(testEntity.getNode().getLabels()))); } catch (FrameworkException fex) { fail("Unexpected exception"); } }
@Test public void shouldProvideTheCorrectRelationshipData() { GraphDatabaseService db = dbRule.getGraphDatabaseService(); // create a rel type so the next type id is non zero try (Transaction tx = db.beginTx()) { db.createNode() .createRelationshipTo(db.createNode(), DynamicRelationshipType.withName("TYPE")); } RelationshipType livesIn = DynamicRelationshipType.withName("LIVES_IN"); long relId; try (Transaction tx = db.beginTx()) { Node person = db.createNode(DynamicLabel.label("Person")); Node city = db.createNode(DynamicLabel.label("City")); Relationship rel = person.createRelationshipTo(city, livesIn); rel.setProperty("since", 2009); relId = rel.getId(); tx.success(); } final Set<String> changedRelationships = new HashSet<>(); db.registerTransactionEventHandler( new TransactionEventHandler.Adapter<Void>() { @Override public Void beforeCommit(TransactionData data) throws Exception { for (PropertyEntry<Relationship> entry : data.assignedRelationshipProperties()) { changedRelationships.add(entry.entity().getType().name()); } return null; } }); try (Transaction tx = db.beginTx()) { Relationship rel = db.getRelationshipById(relId); rel.setProperty("since", 2010); tx.success(); } assertEquals(1, changedRelationships.size()); assertTrue( livesIn + " not in " + changedRelationships.toString(), changedRelationships.contains(livesIn.name())); }
private static List<Double> getWeightVectorForClass( Map<String, List<LinkedHashMap<String, Object>>> documents, String key, List<Integer> featureIndexList, GraphDatabaseService db) { List<Double> weightVector; Transaction tx = db.beginTx(); // Get class id Long classId = db.findNodesByLabelAndProperty(DynamicLabel.label("Class"), "name", key) .iterator() .next() .getId(); // Get weight vector for class List<Long> longs = documents .get(key) .stream() .map(a -> ((Integer) a.get("feature")).longValue()) .collect(Collectors.toList()); weightVector = featureIndexList .stream() .map(i -> longs.contains(i.longValue()) ? tfidf(db, i.longValue(), classId) : 0.0) .collect(Collectors.toList()); tx.success(); tx.close(); return weightVector; }
public Node createNodeUsuario(Usuario usuario) { Node lockNode; try (Transaction tx = getManagerConnection().getGraphDb().beginTx()) { lockNode = getManagerConnection().getGraphDb().createNode(); tx.success(); } try (Transaction tx = getManagerConnection().beginTx()) { Index<Node> usersIndex = getManagerConnection().getGraphDb().index().forNodes("users"); Node userNode = usersIndex.get("login", usuario.getLogin()).getSingle(); if (userNode != null) { return userNode; } tx.acquireWriteLock(lockNode); userNode = usersIndex.get("login", usuario.getLogin()).getSingle(); if (userNode == null) { userNode = getManagerConnection().getGraphDb().createNode(DynamicLabel.label("User")); usersIndex.add(userNode, "login", usuario.getLogin()); userNode.setProperty("login", usuario.getLogin()); userNode.setProperty("nome", usuario.getNome()); userNode.setProperty("senha", usuario.getSenha()); userNode.setProperty("type", usuario.getType().getName()); } tx.success(); return userNode; } }
public static Map<Label, List<ElasticSearchIndexSpec>> parseIndexSpec(String spec) throws ParseException { if (spec == null) { return new LinkedHashMap<Label, List<ElasticSearchIndexSpec>>(); } Map<Label, List<ElasticSearchIndexSpec>> map = new LinkedHashMap<Label, List<ElasticSearchIndexSpec>>(); Matcher matcher = INDEX_SPEC_RE.matcher(spec); while (matcher.find()) { Matcher propsMatcher = PROPS_SPEC_RE.matcher(matcher.group("props")); Set<String> props = new HashSet<String>(); while (propsMatcher.find()) { props.add(propsMatcher.group()); } Label label = DynamicLabel.label(matcher.group("label")); if (map.containsKey(label)) { throw new ParseException(matcher.group(), 0); } map.put( label, new ArrayList<ElasticSearchIndexSpec>( Arrays.asList(new ElasticSearchIndexSpec(matcher.group("indexname"), props)))); } return map; }
private Node setLabels(Node node, Collection<String> labels) { if (labels==null || labels.isEmpty()) return node; for (String label : labels) { node.addLabel(DynamicLabel.label(label)); } return node; }
public class FriendOfAFriendDepth4 { public static final Label USER = DynamicLabel.label("User"); private final TraversalDescription traversalDescription; private final GraphDatabaseService db; public FriendOfAFriendDepth4(GraphDatabaseService db) { this.db = db; traversalDescription = traversalDescription(db); } private TraversalDescription traversalDescription(GraphDatabaseService db) { return db.traversalDescription() .breadthFirst() .uniqueness(NODE_GLOBAL) .relationships(withName("FRIEND")) .evaluator( new Evaluator() { @Override public Evaluation evaluate(Path path) { if (path.length() == 4) { return Evaluation.INCLUDE_AND_PRUNE; } return Evaluation.EXCLUDE_AND_CONTINUE; } }); } public Iterable<Node> getFriends(String name) { ResourceIterable<Node> users = db.findNodesByLabelAndProperty(USER, "name", name); Node startNode = IteratorUtil.single(users); return traversalDescription.traverse(startNode).nodes(); } }
@Test public void insert() throws InterruptedException { // START SNIPPET: insert BatchInserter inserter = null; try { inserter = BatchInserters.inserter( new File("target/batchinserter-example").getAbsolutePath(), fileSystem); Label personLabel = DynamicLabel.label("Person"); inserter.createDeferredSchemaIndex(personLabel).on("name").create(); Map<String, Object> properties = new HashMap<>(); properties.put("name", "Mattias"); long mattiasNode = inserter.createNode(properties, personLabel); properties.put("name", "Chris"); long chrisNode = inserter.createNode(properties, personLabel); RelationshipType knows = DynamicRelationshipType.withName("KNOWS"); inserter.createRelationship(mattiasNode, chrisNode, knows, null); } finally { if (inserter != null) { inserter.shutdown(); } } // END SNIPPET: insert // try it out from a normal db GraphDatabaseService db = new TestGraphDatabaseFactory() .setFileSystem(fileSystem) .newImpermanentDatabase(new File("target/batchinserter-example").getAbsolutePath()); try (Transaction tx = db.beginTx()) { Label personLabelForTesting = DynamicLabel.label("Person"); Node mNode = db.findNode(personLabelForTesting, "name", "Mattias"); Node cNode = mNode .getSingleRelationship(DynamicRelationshipType.withName("KNOWS"), Direction.OUTGOING) .getEndNode(); assertThat((String) cNode.getProperty("name"), is("Chris")); assertThat(db.schema().getIndexes(personLabelForTesting).iterator().hasNext(), is(true)); } finally { db.shutdown(); } }
@Test public void deletedNewLabelShouldNotInfluenceEquality() { // bug test try (Transaction tx = database.beginTx()) { database.createNode(DynamicLabel.label("Accident")); database.createNode(DynamicLabel.label("RealLabel")); tx.success(); } try (Transaction tx = database.beginTx()) { database.getNodeById(0).delete(); tx.success(); } String cypher = "CREATE (n:RealLabel)"; assertSameGraph(database, cypher); }
private Label[] toLabels(Collection<String> labels) { if (labels==null || labels.isEmpty()) return NO_LABELS; Label[] labelArray = new Label[labels.size()]; int i=0; for (String label : labels) { labelArray[i++]= DynamicLabel.label(label); } return labelArray; }
@Test public void listing3_10_node_labels() { usersAndMovies.addLabelToMovies(); try (Transaction tx = graphDb.beginTx()) { ResourceIterable<Node> movies = GlobalGraphOperations.at(graphDb).getAllNodesWithLabel(DynamicLabel.label("MOVIES")); assertEquals(3, IteratorUtil.count(movies)); tx.success(); } }
@Override public Object createVertex( final int id, final String type, final Map<String, ? extends Object> attributes, final Map<String, Object> outgoingEdges, final Map<String, Object> incomingEdges) { final Node node = graphDb.createNode(DynamicLabel.label(type)); // this only works for inheritance hierarchies with if (ModelConstants.SUPERTYPES.containsKey(type)) { final String ancestor = ModelConstants.SUPERTYPES.get(type); node.addLabel(DynamicLabel.label(ancestor)); } for (final Entry<String, ? extends Object> attribute : attributes.entrySet()) { final String key = attribute.getKey(); Object value = attribute.getValue(); // convert the value to string if it's an enum value = enumsToString(value); node.setProperty(key, value); } for (final Entry<String, Object> outgoingEdge : outgoingEdges.entrySet()) { final String label = outgoingEdge.getKey(); if (outgoingEdge.getValue() instanceof Node) { final Node targetNode = (Node) outgoingEdge.getValue(); node.createRelationshipTo(targetNode, relationship(label)); } } for (final Entry<String, Object> incomingEdge : incomingEdges.entrySet()) { final String label = incomingEdge.getKey(); if (incomingEdge.getValue() instanceof Node) { final Node sourceNode = (Node) incomingEdge.getValue(); sourceNode.createRelationshipTo(node, relationship(label)); } } return node; }
private static Node addNode(String name) { Node userNode; try (Transaction tx = graphDb.beginTx()) { Label label = DynamicLabel.label("Nome"); userNode = graphDb.createNode(label); userNode.setProperty("name", name); System.out.println("node created"); tx.success(); } return userNode; }
private static List<Node> getAllClasses(GraphDatabaseService db) { Transaction tx = db.beginTx(); // Get classes using Java API final List<Node> finalClasses = new ArrayList<>(); GlobalGraphOperations.at(db) .getAllNodesWithLabel(DynamicLabel.label("Class")) .forEach(a -> finalClasses.add(a)); tx.success(); tx.close(); return finalClasses.stream().map(a -> a).collect(Collectors.toList()); }
public static int getDocumentSize(GraphDatabaseService db) { int documentSize; String cacheKey = "GLOBAL_DOCUMENT_SIZE"; if (vectorSpaceModelCache.getIfPresent(cacheKey) == null) { documentSize = IteratorUtil.count( GlobalGraphOperations.at(db).getAllNodesWithLabel(DynamicLabel.label("Class"))); vectorSpaceModelCache.put(cacheKey, documentSize); } else { documentSize = (Integer) vectorSpaceModelCache.getIfPresent(cacheKey); } return documentSize; }
private static void setLabelSystem() { IndexDefinition indexDefinition; try (Transaction tx = graphDb.beginTx()) { Schema schema = graphDb.schema(); indexDefinition = schema.indexFor(DynamicLabel.label("Nome")).on("name").create(); tx.success(); } try (Transaction tx = graphDb.beginTx()) { Schema schema = graphDb.schema(); schema.awaitIndexOnline(indexDefinition, 10, TimeUnit.SECONDS); } }
@Override public Vertex addVertex(final Object... keyValues) { ElementHelper.legalPropertyKeyValueArray(keyValues); if (ElementHelper.getIdValue(keyValues).isPresent()) throw Vertex.Exceptions.userSuppliedIdsNotSupported(); final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL); this.tx().readWrite(); final Neo4jVertex vertex = new Neo4jVertex(this.baseGraph.createNode(DynamicLabel.label(label)), this); ElementHelper.attachProperties(vertex, keyValues); return vertex; }
@Test public void listing3_11_node_labels_and_property() { try { usersAndMovies.addLabelToMovies(); } catch (Exception e) { // ignore if index already exist } try (Transaction tx = graphDb.beginTx()) { ResourceIterable<Node> movies = graphDb.findNodesByLabelAndProperty(DynamicLabel.label("MOVIES"), "name", "Fargo"); assertEquals(1, IteratorUtil.count(movies)); tx.success(); } }
private static Node findNodeByName(String nameToFind) { ArrayList<Node> userNodes = new ArrayList<>(); Label label = DynamicLabel.label("Nome"); try (Transaction tx = graphDb.beginTx()) { try (ResourceIterator<Node> users = graphDb.findNodes(label, "name", nameToFind)) { while (users.hasNext()) { userNodes.add(users.next()); } for (Node node : userNodes) { System.out.println("trovato nodo: " + node.getProperty("name")); } } } return userNodes.get(0); }
@Test public void nodeCanBecomeSchemaIndexableInBeforeCommitByAddingLabel() throws Exception { // Given we have a schema index... GraphDatabaseService db = dbRule.getGraphDatabaseService(); final Label label = DynamicLabel.label("Label"); IndexDefinition index; try (Transaction tx = db.beginTx()) { index = db.schema().indexFor(label).on("indexed").create(); tx.success(); } // ... and a transaction event handler that likes to add the indexed property on nodes db.registerTransactionEventHandler( new TransactionEventHandler.Adapter<Object>() { @Override public Object beforeCommit(TransactionData data) throws Exception { Iterator<Node> nodes = data.createdNodes().iterator(); if (nodes.hasNext()) { Node node = nodes.next(); node.addLabel(label); } return null; } }); // When we create a node with the right property, but not the right label... try (Transaction tx = db.beginTx()) { db.schema().awaitIndexesOnline(10, TimeUnit.SECONDS); Node node = db.createNode(); node.setProperty("indexed", "value"); node.setProperty("random", 42); tx.success(); } // Then we should be able to look it up through the index. try (Transaction ignore = db.beginTx()) { Node node = db.findNode(label, "indexed", "value"); assertThat(node.getProperty("random"), is((Object) 42)); } }
private static List<Integer> getFeatureIndexList(GraphDatabaseService db) { Transaction tx = db.beginTx(); // Get classes using Java API final List<Node> patterns = new ArrayList<>(); GlobalGraphOperations.at(db) .getAllNodesWithLabel(DynamicLabel.label("Pattern")) .forEach(a -> patterns.add(a)); Collections.sort( patterns, (a, b) -> ((Integer) b.getProperty("threshold")) .compareTo(((Integer) a.getProperty("threshold")))); List<Integer> patternIds = patterns.stream().map(a -> ((Long) a.getId()).intValue()).collect(Collectors.toList()); tx.success(); tx.close(); return patternIds; }
protected void verifyData(int nodeCount, GraphDatabaseService db) { // Verify that all the labels are in place Set<Label> expectedLabels = new HashSet<>(); for (String label : LABELS) { expectedLabels.add(DynamicLabel.label(label)); } GlobalGraphOperations globalOps = GlobalGraphOperations.at(db); Set<Label> allLabels = Iterables.toSet(globalOps.getAllLabels()); assertThat(allLabels, is(expectedLabels)); // Sample some nodes for deeper inspection of their contents Random random = new Random(); for (int i = 0; i < nodeCount / 10; i++) { Node node = db.getNodeById(random.nextInt(nodeCount)); int count = count(node.getRelationships()); assertEquals("For node " + node, count, node.getDegree()); for (String key : node.getPropertyKeys()) { node.getProperty(key); Set<Label> actualLabels = Iterables.toSet(node.getLabels()); assertThat(actualLabels, is(expectedLabels)); } } }
public class HaCountsIT { @Test public void shouldUpdateCountsOnSlavesWhenCreatingANodeOnMaster() throws Exception { // when creating a node on the master createANode(master, LABEL, PROPERTY_VALUE, PROPERTY_NAME); // and the slaves got the updates cluster.sync(master); // then the slaves has updated counts assertOnNodeCounts(1, 1, LABEL, master); assertOnNodeCounts(1, 1, LABEL, slave1); assertOnNodeCounts(1, 1, LABEL, slave2); } @Test public void shouldUpdateCountsOnMasterAndSlaveWhenCreatingANodeOnSlave() throws Exception { // when creating a node on the slave createANode(slave1, LABEL, PROPERTY_VALUE, PROPERTY_NAME); // and the master and slave2 got the updates cluster.sync(slave1); // then the master and the other slave have updated counts assertOnNodeCounts(1, 1, LABEL, master); assertOnNodeCounts(1, 1, LABEL, slave1); assertOnNodeCounts(1, 1, LABEL, slave2); } @Test public void shouldUpdateCountsOnSlavesWhenCreatingAnIndexOnMaster() throws Exception { // when creating a node on the master createANode(master, LABEL, PROPERTY_VALUE, PROPERTY_NAME); IndexDescriptor indexDescriptor = createAnIndex(master, LABEL, PROPERTY_NAME); awaitOnline(master, indexDescriptor); // and the slaves got the updates cluster.sync(master); awaitOnline(slave1, indexDescriptor); awaitOnline(slave2, indexDescriptor); // then the slaves has updated counts assertOnIndexCounts(0, 1, 1, 1, indexDescriptor, master); assertOnIndexCounts(0, 1, 1, 1, indexDescriptor, slave1); assertOnIndexCounts(0, 1, 1, 1, indexDescriptor, slave2); } @Test public void shouldUpdateCountsOnClusterWhenCreatingANodeOnSlaveAndAnIndexOnMaster() throws Exception { // when creating a node on the master createANode(slave1, LABEL, PROPERTY_VALUE, PROPERTY_NAME); IndexDescriptor indexDescriptor = createAnIndex(master, LABEL, PROPERTY_NAME); awaitOnline(master, indexDescriptor); // and the updates are propagate in the cluster cluster.sync(); awaitOnline(slave1, indexDescriptor); awaitOnline(slave2, indexDescriptor); // then the slaves has updated counts assertOnIndexCounts(0, 1, 1, 1, indexDescriptor, master); assertOnIndexCounts(0, 1, 1, 1, indexDescriptor, slave1); assertOnIndexCounts(0, 1, 1, 1, indexDescriptor, slave2); } private void createANode( HighlyAvailableGraphDatabase db, Label label, String value, String property) { try (Transaction tx = db.beginTx()) { Node node = db.createNode(label); node.setProperty(property, value); tx.success(); } } private IndexDescriptor createAnIndex( HighlyAvailableGraphDatabase db, Label label, String propertyName) throws KernelException { try (Transaction tx = db.beginTx()) { Statement statement = statement(db); int labelId = statement.tokenWriteOperations().labelGetOrCreateForName(label.name()); int propertyKeyId = statement.tokenWriteOperations().propertyKeyGetOrCreateForName(propertyName); IndexDescriptor index = statement.schemaWriteOperations().indexCreate(labelId, propertyKeyId); tx.success(); return index; } } private void assertOnNodeCounts( int expectedTotalNodes, int expectedLabelledNodes, Label label, HighlyAvailableGraphDatabase db) { try (Transaction ignored = db.beginTx()) { final Statement statement = statement(db); final int labelId = statement.readOperations().labelGetForName(label.name()); assertEquals(expectedTotalNodes, statement.readOperations().countsForNode(-1)); assertEquals(expectedLabelledNodes, statement.readOperations().countsForNode(labelId)); } } private void assertOnIndexCounts( int expectedIndexUpdates, int expectedIndexSize, int expectedUniqueValues, int expectedSampleSize, IndexDescriptor indexDescriptor, HighlyAvailableGraphDatabase db) { CountsTracker counts = counts(db); int labelId = indexDescriptor.getLabelId(); int propertyKeyId = indexDescriptor.getPropertyKeyId(); assertDoubleLongEquals( expectedIndexUpdates, expectedIndexSize, counts.indexUpdatesAndSize(labelId, propertyKeyId, newDoubleLongRegister())); assertDoubleLongEquals( expectedUniqueValues, expectedSampleSize, counts.indexSample(labelId, propertyKeyId, newDoubleLongRegister())); } private void assertDoubleLongEquals( int expectedFirst, int expectedSecond, DoubleLongRegister actualValues) { String msg = String.format( "Expected (%d,%d) but was (%d,%d)", expectedFirst, expectedSecond, actualValues.readFirst(), actualValues.readSecond()); assertTrue(msg, actualValues.hasValues(expectedFirst, expectedSecond)); } private CountsTracker counts(HighlyAvailableGraphDatabase db) { return db.getDependencyResolver().resolveDependency(NeoStore.class).getCounts(); } private Statement statement(HighlyAvailableGraphDatabase db) { return db.getDependencyResolver().resolveDependency(ThreadToStatementContextBridge.class).get(); } private IndexDescriptor awaitOnline(HighlyAvailableGraphDatabase db, IndexDescriptor index) throws KernelException { long start = System.currentTimeMillis(); long end = start + 3000; while (System.currentTimeMillis() < end) { try (Transaction tx = db.beginTx()) { switch (statement(db).readOperations().indexGetState(index)) { case ONLINE: return index; case FAILED: throw new IllegalStateException("Index failed instead of becoming ONLINE"); default: break; } tx.success(); try { Thread.sleep(100); } catch (InterruptedException e) { // ignored } } } throw new IllegalStateException("Index did not become ONLINE within reasonable time"); } private static final Label LABEL = DynamicLabel.label("label"); private static final String PROPERTY_NAME = "prop"; private static final String PROPERTY_VALUE = "value"; @Rule public TargetDirectory.TestDirectory dir = TargetDirectory.testDirForTest(getClass()); private ClusterManager clusterManager; private ClusterManager.ManagedCluster cluster; private HighlyAvailableGraphDatabase master; private HighlyAvailableGraphDatabase slave1; private HighlyAvailableGraphDatabase slave2; @Before public void setup() throws Throwable { clusterManager = new ClusterManager(clusterOfSize(3), dir.graphDbDir(), stringMap()); clusterManager.start(); cluster = clusterManager.getDefaultCluster(); cluster.await(ClusterManager.allSeesAllAsAvailable()); master = cluster.getMaster(); slave1 = cluster.getAnySlave(); slave2 = cluster.getAnySlave(slave1); } @After public void teardown() throws Throwable { clusterManager.shutdown(); } }
@Override public boolean include(Node node) { return !(node.hasLabel(DynamicLabel.label("ChangeSet"))); }
@Override public boolean include(Node node) { return node.hasLabel(DynamicLabel.label("Blue")); }
public void _addLabels(Node node, String[] labels) { for (String label : labels) node.addLabel(DynamicLabel.label(label)); }
public void _addLabel(Node node, String label) { node.addLabel(DynamicLabel.label(label)); }
public Label getLabel() { return DynamicLabel.label("BaseLabel"); }
private List<Node> _findRelatedNodes(GraphKey key) { return _findRelatedNodes(DynamicLabel.label(key.getIndex()), key.getKey(), key.getValue()); }