public double getNodeOutDegree(Node node) { Iterable<Relationship> rel = node.getRelationships(Direction.INCOMING, RelTypes.SIMILAR); return (double) (IteratorUtil.count(rel)); }
private static void getNodeHashMap(Long id, GraphDatabaseService gdb, Cache<Long, HashMap<String, Object>> cache) { Node thisNode = gdb.getNodeById(id); List<String> keys = new ArrayList<>(); HashMap<String, Object> nodeMap = new HashMap<>(); IteratorUtil.addToCollection(thisNode.getPropertyKeys(), keys) .stream() .forEach(n -> nodeMap.put(n, thisNode.getProperty(n))); nodeMap.put("id", id); cache.put(id, nodeMap); }
public static Node getReferenceNode(GraphDatabaseService db, String name) { if (engine == null || db != dbRef) { engine = new ExecutionEngine(db); ReferenceNodes.dbRef = db; } ExecutionResult result = engine.execute("MERGE (ref:ReferenceNode {name:{name}}) RETURN ref", map("name", name)); return IteratorUtil.single(result.<Node>columnAs("ref")); } }
@Test public void shouldReportOwningNodeRecordNotPointingBack() throws Exception { // given long nodeId = 12l; Collection<DynamicRecord> validLabelRecords = new ArrayList<>(); allocateFromNumbers( validLabelRecords, new long[] {nodeId}, iterator( inUse( new DynamicRecord( 0 ) ) ), RECORD_ALLOCATOR ); Collection<DynamicRecord> fakePointedToRecords = new ArrayList<>(); allocateFromNumbers( fakePointedToRecords, new long[] {nodeId}, iterator( inUse( new DynamicRecord( 1 ) ) ), RECORD_ALLOCATOR ); NodeRecord nodeRecord = inUse( new NodeRecord( nodeId, false, -1, -1 ) ); nodeRecord.setLabelField( dynamicPointer( fakePointedToRecords ), fakePointedToRecords ); add( nodeRecord ); // when DynamicLabelConsistencyReport report = check( single( validLabelRecords.iterator() ) ); // then verify( report ).orphanDynamicLabelRecordDueToInvalidOwner( nodeRecord ); } }
@Test public void exampleQuery() throws Exception { // START SNIPPET: JavaQuery ExecutionEngine engine = new ExecutionEngine( db ); ExecutionResult result = engine.execute( "START n=node(0) WHERE 1=1 RETURN n" ); assertThat( result.columns(), hasItem( "n" ) ); Iterator<Node> n_column = result.columnAs( "n" ); assertThat( asIterable( n_column ), hasItem( db.getNodeById( 0 ) ) ); // END SNIPPET: JavaQuery }
List<Path> paths = IteratorUtil.asCollection(db.traversalDescription() .depthFirst() .relationships(withName("HAS_AFFINITY"), Direction.BOTH)
private void assertNodeEquals( InputNode input, Node node ) { // properties assertPropertiesEquals( input, node ); // labels Set<String> expectedLabels = asSet( input.labels() ); for ( Label label : node.getLabels() ) { assertTrue( expectedLabels.remove( label.name() ) ); } assertTrue( expectedLabels.isEmpty() ); }
@Override public void addPairing(FlavorPair flavorPair) { Ingredient ingredient1 = IteratorUtil.firstOrNull(ingredientRepository.findByName(flavorPair.getIngredient1())); Ingredient ingredient2 = IteratorUtil.firstOrNull(ingredientRepository.findByName(flavorPair.getIngredient2())); Pairing pairing; if (ingredient1 != null && ingredient2 != null) {
for ( Node node : IteratorUtil.asIterable( n_column ) )
public static Map<Long, Integer> getTermFrequencyMapForDocument(GraphDatabaseService db, Long classId) { Map<Long, Integer> termDocumentMatrix; String cacheKey = "TERM_DOCUMENT_FREQUENCY_" + classId; if(vectorSpaceModelCache.getIfPresent(cacheKey) == null) { Node classNode = db.getNodeById(classId); termDocumentMatrix = new HashMap<>(); IteratorUtil.asCollection(db.traversalDescription() .depthFirst() .relationships(withName("HAS_CLASS"), Direction.INCOMING) .evaluator(Evaluators.fromDepth(1)) .evaluator(Evaluators.toDepth(1)) .traverse(classNode)).stream() .forEach(p -> { int matches = (Integer) p.lastRelationship().getProperty("matches"); termDocumentMatrix.put(p.endNode().getId(), matches); }); vectorSpaceModelCache.put(cacheKey, termDocumentMatrix); } else { termDocumentMatrix = (Map<Long, Integer>)vectorSpaceModelCache.getIfPresent(cacheKey); } return termDocumentMatrix; }
public double getNodeInDegree(Node node) { Iterable<Relationship> rel = node.getRelationships(Direction.OUTGOING, RelTypes.SIMILAR); return (double) (IteratorUtil.count(rel)); }
private <T> List<T> toList( ExecutionResult result, String column ) { List<T> results = new ArrayList<T>(); IteratorUtil.addToCollection( result.<T>columnAs( column ), results ); return results; }
@Test public void shouldReportLabelScanStoreInconsistencies() throws Exception { // given GraphStoreFixture.IdGenerator idGenerator = fixture.idGenerator(); long nodeId1 = idGenerator.node(); long labelId = idGenerator.label() - 1; LabelScanStore labelScanStore = fixture.directStoreAccess().labelScanStore(); Iterable<NodeLabelUpdate> nodeLabelUpdates = asIterable( labelChanges( nodeId1, new long[]{}, new long[]{labelId} ) ); write( labelScanStore, nodeLabelUpdates ); // when ConsistencySummaryStatistics stats = check(); // then on( stats ).verify( RecordType.LABEL_SCAN_DOCUMENT, 1 ) .andThatsAllFolks(); }
public static double getFeatureMatchDistribution(GraphDatabaseService db, Long patternId) { Transaction tx = db.beginTx(); Node startNode = db.getNodeById(patternId); // Feature match distribution List<Double> matches = IteratorUtil.asCollection(db.traversalDescription() .depthFirst() .relationships(withName("HAS_CLASS"), Direction.OUTGOING) .evaluator(Evaluators.fromDepth(1)) .evaluator(Evaluators.toDepth(1)) .traverse(startNode) .relationships()) .stream() .map(p -> ((Integer)p.getProperty("matches")).doubleValue()) .collect(Collectors.toList()); tx.success(); tx.close(); double variance = 1.0; if(matches.size() > 1) { Double[] matchArr = matches.toArray(new Double[matches.size()]); // Get the standard deviation DescriptiveStatistics ds = new DescriptiveStatistics(); matches.forEach(m -> ds.addValue(m.doubleValue() / StatUtils.sum(ArrayUtils.toPrimitive(matchArr)))); variance = ds.getStandardDeviation(); } return variance; }
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; }
public List<Node> friendsThatCanIntroduceMeTo(Node me, final Node target, Uniqueness uniqueness) { TraversalDescription description = Traversal.description() .relationships(KNOWS) .relationships(IS_FRIEND_OF) .evaluator(new Evaluator() { @Override public Evaluation evaluate(Path path) { Node currentNode = path.endNode(); if (currentNode.getId() == target.getId()) { return Evaluation.EXCLUDE_AND_PRUNE; } Path singlePath = GraphAlgoFactory.shortestPath(Traversal.expanderForTypes(KNOWS, Direction.BOTH, IS_FRIEND_OF, Direction.BOTH), 1).findSinglePath(currentNode, target); if (singlePath != null) { //direct link exists return Evaluation.INCLUDE_AND_CONTINUE; } else { return Evaluation.EXCLUDE_AND_CONTINUE; } } }) // .evaluator(Evaluators.atDepth(1)) .uniqueness(uniqueness); Iterable<Node> nodes = description.traverse(me).nodes(); ArrayList<Node> result = new ArrayList<Node>(); IteratorUtil.addToCollection(nodes, result); return result; }
Relationship rel = IteratorUtil.asCollection(db.traversalDescription() .depthFirst() .relationships(withName(getRelationshipType()), Direction.OUTGOING)
@Test public void create_node_using_create_unique_with_java_maps() throws Exception { Map<String, Object> props = new HashMap<String, Object>(); props.put( "name", "Andres" ); props.put( "position", "Developer" ); Map<String, Object> params = new HashMap<String, Object>(); params.put( "props", props ); String query = "START n=node(0) CREATE UNIQUE p = n-[:REL]->({props}) RETURN last(nodes(p)) AS X"; ExecutionResult result = engine.execute( query, params ); assertThat( count( result ), is( 1 ) ); }
public List<Path> pathThatICanUseToIntroduceMeTo(Node me, final Node target, Uniqueness uniqueness) { TraversalDescription description = Traversal.description() .relationships(KNOWS) .relationships(IS_FRIEND_OF) .evaluator(new Evaluator() { @Override public Evaluation evaluate(Path path) { Node currentNode = path.endNode(); if (currentNode.getId() == target.getId()) { return Evaluation.EXCLUDE_AND_PRUNE; } Path singlePath = GraphAlgoFactory.shortestPath(Traversal.expanderForTypes(KNOWS, Direction.BOTH, IS_FRIEND_OF, Direction.BOTH), 1).findSinglePath(currentNode, target); if (singlePath != null) { //direct link exists return Evaluation.INCLUDE_AND_CONTINUE; } else { return Evaluation.EXCLUDE_AND_CONTINUE; } } }) .uniqueness(uniqueness); ArrayList<Path> result = new ArrayList<Path>(); try (Transaction tx = graphDb.beginTx()) { IteratorUtil.addToCollection(description.traverse(me).iterator(), result); } return result; } }
@Test public void should_be_able_to_handle_two_params_without_named_nodes() throws Exception { Map<String, Object> props1 = new HashMap<String, Object>(); props1.put( "name", "Andres" ); props1.put( "position", "Developer" ); Map<String, Object> props2 = new HashMap<String, Object>(); props2.put( "name", "Lasse" ); props2.put( "awesome", "true" ); Map<String, Object> params = new HashMap<String, Object>(); params.put( "props1", props1 ); params.put( "props2", props2 ); String query = "START n=node(0) CREATE UNIQUE p = n-[:REL]->({props1})-[:LER]->({props2}) RETURN p"; ExecutionResult result = engine.execute( query, params ); assertThat( count( result ), is( 1 ) ); }