private static List<LinkedHashMap<String, Object>> getFeaturesForClass(
      GraphDatabaseService db, Node classNode) {
    List<LinkedHashMap<String, Object>> patternIds = new ArrayList<>();

    for (Path p :
        db.traversalDescription()
            .depthFirst()
            .relationships(withName("HAS_CLASS"), Direction.INCOMING)
            .evaluator(Evaluators.fromDepth(1))
            .evaluator(Evaluators.toDepth(1))
            .traverse(classNode)) {

      LinkedHashMap<String, Object> featureMap = new LinkedHashMap<>();

      if (p.relationships().iterator().hasNext()) {
        featureMap.put("frequency", p.relationships().iterator().next().getProperty("matches"));
      } else {
        featureMap.put("frequency", 0);
      }

      featureMap.put("feature", ((Long) p.endNode().getId()).intValue());

      patternIds.add(featureMap);
    }
    return patternIds;
  }
  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 ->
                  termDocumentMatrix.put(
                      p.endNode().getId(), (Integer) p.lastRelationship().getProperty("matches")));

      vectorSpaceModelCache.put(cacheKey, termDocumentMatrix);
    } else {
      termDocumentMatrix = (Map<Long, Integer>) vectorSpaceModelCache.getIfPresent(cacheKey);
    }

    return termDocumentMatrix;
  }
 private TraversalDescription friendToSuggestionTraversalDescription() {
   return Traversal.description()
       .breadthFirst()
       .relationships(ConnectionType.KNOWS)
       .evaluator(Evaluators.excludeStartPosition())
       .evaluator(Evaluators.atDepth(2));
 }
  public static int getDocumentSizeForFeature(GraphDatabaseService db, Long id) {
    int documentSize;

    String cacheKey = "DOCUMENT_SIZE_FEATURE_" + id;

    if (vectorSpaceModelCache.getIfPresent(cacheKey) == null) {
      Node startNode = db.getNodeById(id);

      Iterator<Node> classes =
          db.traversalDescription()
              .depthFirst()
              .relationships(withName("HAS_CLASS"), Direction.OUTGOING)
              .evaluator(Evaluators.fromDepth(1))
              .evaluator(Evaluators.toDepth(1))
              .traverse(startNode)
              .nodes()
              .iterator();

      documentSize = IteratorUtil.count(classes);

      vectorSpaceModelCache.put(cacheKey, documentSize);
    } else {
      documentSize = (Integer) vectorSpaceModelCache.getIfPresent(cacheKey);
    }

    return documentSize;
  }
 private void checkGeometryNodeIterator() {
   TraversalDescription td =
       database
           .traversalDescription()
           .depthFirst()
           .relationships(RTreeRelationshipTypes.RTREE_REFERENCE, Direction.OUTGOING)
           .evaluator(Evaluators.excludeStartPosition())
           .evaluator(Evaluators.toDepth(1));
   while ((geometryNodeIterator == null || !geometryNodeIterator.hasNext())
       && allIndexNodeIterator.hasNext()) {
     geometryNodeIterator = td.traverse(allIndexNodeIterator.next()).nodes().iterator();
   }
 }
 @SuppressWarnings("deprecation")
 @Test
 @Transactional
 public void testTraverse() throws Exception {
   // final TraversalDescription description =
   // Traversal.description().relationships(KNOWS).prune(Traversal.pruneAfterDepth(1)).filter(Traversal.returnAllButStartNode());
   final TraversalDescription description =
       Traversal.description()
           .relationships(KNOWS)
           .evaluator(Evaluators.toDepth(1))
           .evaluator(Evaluators.excludeStartPosition());
   assertSingleResult(
       "node1",
       neo4jTemplate
           .traverse(referenceNode, description)
           .to(String.class, new PathNodeNameMapper()));
 }
 public Iterable<Node> getAllIndexInternalNodes() {
   TraversalDescription td =
       database
           .traversalDescription()
           .breadthFirst()
           .relationships(RTreeRelationshipTypes.RTREE_CHILD, Direction.OUTGOING)
           .evaluator(Evaluators.excludeStartPosition());
   return td.traverse(getIndexRoot()).nodes();
 }
  private void canPreFilterNodes(TraversalDescription description) {
    Traverser traverser =
        description
            .uniqueness(Uniqueness.NONE)
            .evaluator(Evaluators.atDepth(2))
            .traverse(referenceNode());

    expectPaths(traverser, "1,2,6", "1,3,5", "1,4,5", "1,5,3", "1,5,4", "1,5,6");
  }
  private void canPruneTraversalAtSpecificDepth(TraversalDescription description) {
    Traverser traverser =
        description
            .uniqueness(Uniqueness.NONE)
            .evaluator(Evaluators.toDepth(1))
            .traverse(referenceNode());

    expectNodes(traverser, "1", "2", "3", "4", "5");
  }
Exemple #10
0
  public Iterable<WeightedPath> findAllPaths(Node start, final Node end) {
    lastTraverser =
        TRAVERSAL
            .expand(expander, stateFactory)
            .order(new SelectorFactory(costEvaluator))
            .evaluator(Evaluators.includeWhereEndNodeIs(end))
            .traverse(start);

    // Here's how the bidirectional equivalent would look
    //        lastTraverser = Traversal.bidirectionalTraversal()
    //                .mirroredSides( TRAVERSAL.expand( expander ).order( new SelectorFactory(
    // costEvaluator ) ) )
    //                .traverse( start, end );

    return new Iterable<WeightedPath>() {
      public Iterator<WeightedPath> iterator() {
        return new StopAfterWeightIterator(lastTraverser.iterator(), costEvaluator);
      }
    };
  }
 @Test
 public void getAllGroups() throws Exception {
   Transaction tx = graphDb.beginTx();
   try {
     System.out.println("All groups:");
     // START SNIPPET: get-groups
     Node referenceNode = graphDb.getReferenceNode();
     TraversalDescription td =
         Traversal.description()
             .breadthFirst()
             .relationships(RoleRels.ROOT, Direction.INCOMING)
             .relationships(RoleRels.PART_OF, Direction.INCOMING)
             .evaluator(Evaluators.excludeStartPosition());
     for (Node group : td.traverse(referenceNode).nodes()) {
       System.out.println(group.getProperty(NAME));
     }
     // END SNIPPET: get-groups
     tx.success();
   } finally {
     tx.finish();
   }
 }
  public RelationshipFollowingResource(
      SecurityContext securityContext, TypedIdResource typedIdResource) {

    this.traversalDescription =
        Traversal.description()
            .depthFirst()
            .uniqueness(Uniqueness.NODE_GLOBAL)
            .evaluator(Evaluators.excludeStartPosition());
    this.visitedRelationships = new LinkedHashSet<AbstractRelationProperty>();
    this.securityContext = securityContext;
    this.idSet = new LinkedHashSet<Object>();
    this.uriParts = new LinkedList<String>();

    // add TypedIdResource to list of evaluators
    traversalDescription = traversalDescription.evaluator(this);

    // store first and last constraint separately
    // to be able to access them faster afterwards
    firstResource = typedIdResource;
    lastResource = typedIdResource;

    UuidResource idResource = typedIdResource.getIdResource();

    if (idResource instanceof UuidResource) {

      logger.log(Level.FINE, "Adding id {0} to id set", idResource.getUriPart());

      // add uuid from TypedIdResource to idSet
      idSet.add(((UuidResource) idResource).getUriPart());

    } else {

      logger.log(Level.FINE, "Adding id {0} to id set", idResource.getUriPart());

      // add id from TypedIdResource to idSet
      idSet.add(idResource.getUuid());
    }
  }
 @Test
 public void getJalesMemberships() throws Exception {
   Transaction tx = graphDb.beginTx();
   try {
     System.out.println("Jale's memberships:");
     // START SNIPPET: get-user-memberships
     Node jale = getUserByName("Jale");
     TraversalDescription td =
         Traversal.description()
             .depthFirst()
             .relationships(RoleRels.MEMBER_OF, Direction.OUTGOING)
             .relationships(RoleRels.PART_OF, Direction.OUTGOING)
             .evaluator(Evaluators.excludeStartPosition());
     for (Path path : td.traverse(jale)) {
       Node membership = path.endNode();
       System.out.println(membership.getProperty(NAME) + " " + (path.length() - 1));
     }
     // END SNIPPET: get-user-memberships
     tx.success();
   } finally {
     tx.finish();
   }
 }
 @Test
 public void getAllAdmins() {
   Transaction tx = graphDb.beginTx();
   try {
     System.out.println("All admins:");
     // START SNIPPET: get-admins
     Node admins = getGroupByName("Admins");
     TraversalDescription td =
         Traversal.description()
             .breadthFirst()
             .relationships(RoleRels.PART_OF, Direction.INCOMING)
             .relationships(RoleRels.MEMBER_OF, Direction.INCOMING)
             .evaluator(Evaluators.excludeStartPosition());
     for (Path path : td.traverse(admins)) {
       Node part = path.endNode();
       System.out.println(part.getProperty(NAME) + " " + (path.length() - 1));
     }
     // END SNIPPET: get-admins
     tx.success();
   } finally {
     tx.finish();
   }
 }
Exemple #15
0
 /** @deprecated See {@link org.neo4j.graphdb.traversal.BranchCollisionPolicies#SHORTEST_PATH} */
 @Deprecated
 public static BranchCollisionDetector shortestPathsCollisionDetector(int maxDepth) {
   return new ShortestPathsBranchCollisionDetector(Evaluators.toDepth(maxDepth));
 }