Java 类org.neo4j.graphdb.index.IndexHits 实例源码

项目:EvilCoder    文件:Traversals.java   
public static List<Node> getCallsTo(String source)
    {
        List<Node> retval = new LinkedList<Node>();

// JANNIK
        String my = source;
        my = my.replace("*", "\\*");
        my = my.replace("(", "\\(");
        my = my.replace(")", "\\)");
        my = my.replace("-", "\\-");
        my = my.replace(" ", "\\ ");

        String query = String.format("%s:Callee AND %s:%s", NodeKeys.TYPE, NodeKeys.CODE, my);
        IndexHits<Node> hits = Neo4JDBInterface.queryIndex(query);
        for (Node n : hits)
        {
            List<Node> parents = getParentsConnectedBy(n, "IS_AST_PARENT");
            retval.add(parents.get(0));
        }
        return retval;
    }
项目:EvilCoder    文件:Traversals.java   
public static List<Node> getCallsToForFunction(String source,
            long functionId)
    {
        List<Node> retval = new LinkedList<Node>();
// JANNIK
        String my = source;
        my = my.replace("*", "\\*");
        my = my.replace("(", "\\(");
        my = my.replace(")", "\\)");
        my = my.replace("-", "\\-");
        my = my.replace(" ", "\\ ");

        String query = String.format("%s:Callee AND %s:%s AND %s:%s", NodeKeys.TYPE, NodeKeys.FUNCTION_ID, functionId, NodeKeys.CODE, my);

        IndexHits<Node> hits = Neo4JDBInterface.queryIndex(query);
        for (Node n : hits)
        {
            List<Node> parents = getParentsConnectedBy(n, "IS_AST_PARENT");
            retval.add(parents.get(0));
        }
        return retval;
    }
项目:neo4j-lucene5-index    文件:RelatedNodesQuestionTest.java   
@Test
public void question5346011()
{
    GraphDatabaseService service = new TestGraphDatabaseFactory().newImpermanentDatabase();
    try ( Transaction tx = service.beginTx() )
    {
        RelationshipIndex index = service.index().forRelationships( "exact" );
        // ...creation of the nodes and relationship
        Node node1 = service.createNode();
        Node node2 = service.createNode();
        String a_uuid = "xyz";
        Relationship relationship = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "related" ) );
        index.add( relationship, "uuid", a_uuid );
        // query
        IndexHits<Relationship> hits = index.get( "uuid", a_uuid, node1, node2 );
        assertEquals( 1, hits.size() );
        tx.success();
    }
    service.shutdown();
}
项目:neo4j-lucene5-index    文件:Contains.java   
@Override
public boolean matchesSafely( IndexHits<T> indexHits )
{
    Collection<T> collection = IteratorUtil.asCollection( indexHits.iterator() );

    if ( expectedItems.length != collection.size() )
    {
        message = "IndexHits with a size of " + expectedItems.length + ", got one with " + collection.size();
        message += collection.toString();
        return false;
    }

    for ( T item : expectedItems )
    {
        if ( !collection.contains( item ) )
        {
            message = "Item (" + item + ") not found.";
            return false;
        }

    }
    return true;
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void testScoring()
{
    Index<Node> index = nodeIndex( LuceneIndexImplementation.FULLTEXT_CONFIG );
    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    String key = "text";
    // Where the heck did I get this sentence from?
    index.add( node1, key, "a time where no one was really awake" );
    index.add( node2, key, "once upon a time there was" );
    restartTx();

    IndexHits<Node> hits = index.query( key, new QueryContext( "once upon a time was" ).sort( Sort.RELEVANCE ) );
    Node hit1 = hits.next();
    float score1 = hits.currentScore();
    Node hit2 = hits.next();
    float score2 = hits.currentScore();
    assertEquals( node2, hit1 );
    assertEquals( node1, hit2 );
    assertTrue( "Score 1 (" + score1 + ") should have been higher than score 2 (" + score2 + ")", score1 > score2 );
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void testCombinedHitsSizeProblem()
{
    Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG );
    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Node node3 = graphDb.createNode();
    String key = "key";
    String value = "value";
    index.add( node1, key, value );
    index.add( node2, key, value );
    restartTx();
    index.add( node3, key, value );
    IndexHits<Node> hits = index.get( key, value );
    assertEquals( 3, hits.size() );
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void shouldNotFindValueDeletedInSameTx()
{
    Index<Node> nodeIndex = graphDb.index().forNodes( "size-after-removal" );
    Node node = graphDb.createNode();
    nodeIndex.add( node, "key", "value" );
    restartTx();

    nodeIndex.remove( node );
    for ( int i = 0; i < 2; i++ )
    {
        IndexHits<Node> hits = nodeIndex.get( "key", "value" );
        assertEquals( 0, hits.size() );
        assertNull( hits.getSingle() );
        hits.close();
        restartTx();
    }
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void shouldNotSeeDeletedRelationshipWhenQueryingWithStartAndEndNode()
{
    // GIVEN
    RelationshipIndex index = relationshipIndex( EXACT_CONFIG );
    Node start = graphDb.createNode();
    Node end = graphDb.createNode();
    RelationshipType type = withName( "REL" );
    Relationship rel = start.createRelationshipTo( end, type );
    index.add( rel, "Type", type.name() );
    finishTx( true );
    beginTx();

    // WHEN
    IndexHits<Relationship> hits = index.get( "Type", type.name(), start, end );
    assertEquals( 1, count( (Iterator<Relationship>)hits ) );
    assertEquals( 1, hits.size() );
    index.remove( rel );

    // THEN
    hits = index.get( "Type", type.name(), start, end );
    assertEquals( 0, count( (Iterator<Relationship>)hits ) );
    assertEquals( 0, hits.size() );
}
项目:neo4j-lucene5-index    文件:TestIndexDeletion.java   
@Test
public void indexDeletesShouldNotByVisibleUntilCommit() throws Exception
{
    commitTx();

    WorkThread firstTx = createWorker( "First" );

    firstTx.beginTransaction();
    firstTx.removeFromIndex( key, value );

    try ( Transaction transaction = graphDb.beginTx() )
    {
        IndexHits<Node> indexHits = index.get( key, value );
        assertThat( indexHits, contains( node ) );
    }

    firstTx.rollback();
}
项目:neo4j-lucene5-index    文件:DocValuesCollectorTest.java   
@Test
public void shouldReturnIndexHitsInIndexOrderWhenNoSortIsGiven() throws Exception
{
    // given
    DocValuesCollector collector = new DocValuesCollector();
    IndexReaderStub readerStub = indexReaderWithMaxDocs( 42 );

    // when
    collector.doSetNextReader( readerStub.getContext() );
    collector.collect( 1 );
    collector.collect( 2 );

    // then
    IndexHits<Document> indexHits = collector.getIndexHits( null );
    assertEquals( 2, indexHits.size() );
    assertEquals( "1", indexHits.next().get( "id" ) );
    assertEquals( "2", indexHits.next().get( "id" ) );
    assertFalse( indexHits.hasNext() );
}
项目:neo4j-lucene5-index    文件:DocValuesCollectorTest.java   
@Test
public void shouldReturnIndexHitsOrderedByRelevance() throws Exception
{
    // given
    DocValuesCollector collector = new DocValuesCollector( true );
    IndexReaderStub readerStub = indexReaderWithMaxDocs( 42 );

    // when
    collector.doSetNextReader( readerStub.getContext() );
    collector.setScorer( constantScorer( 1.0f ) );
    collector.collect( 1 );
    collector.setScorer( constantScorer( 2.0f ) );
    collector.collect( 2 );


    // then
    IndexHits<Document> indexHits = collector.getIndexHits( Sort.RELEVANCE );
    assertEquals( 2, indexHits.size() );
    assertEquals( "2", indexHits.next().get( "id" ) );
    assertEquals( 2.0f, indexHits.currentScore(), 0.0f );
    assertEquals( "1", indexHits.next().get( "id" ) );
    assertEquals( 1.0f, indexHits.currentScore(), 0.0f );
    assertFalse( indexHits.hasNext() );
}
项目:neo4j-lucene5-index    文件:DocValuesCollectorTest.java   
@Test
public void shouldReturnIndexHitsInGivenSortOrder() throws Exception
{
    // given
    DocValuesCollector collector = new DocValuesCollector( false );
    IndexReaderStub readerStub = indexReaderWithMaxDocs( 43 );

    // when
    collector.doSetNextReader( readerStub.getContext() );
    collector.collect( 1 );
    collector.collect( 3 );
    collector.collect( 37 );
    collector.collect( 42 );

    // then
    Sort byIdDescending = new Sort( new SortField( "id", SortField.Type.LONG, true ) );
    IndexHits<Document> indexHits = collector.getIndexHits( byIdDescending );
    assertEquals( 4, indexHits.size() );
    assertEquals( "42", indexHits.next().get( "id" ) );
    assertEquals( "37", indexHits.next().get( "id" ) );
    assertEquals( "3", indexHits.next().get( "id" ) );
    assertEquals( "1", indexHits.next().get( "id" ) );
    assertFalse( indexHits.hasNext() );
}
项目:neo4j-lucene5-index    文件:DocValuesCollectorTest.java   
@Test
public void shouldSilentlyMergeAllSegments() throws Exception
{
    // given
    DocValuesCollector collector = new DocValuesCollector( false );
    IndexReaderStub readerStub = indexReaderWithMaxDocs( 42 );

    // when
    collector.doSetNextReader( readerStub.getContext() );
    collector.collect( 1 );
    collector.doSetNextReader( readerStub.getContext() );
    collector.collect( 2 );

    // then
    IndexHits<Document> indexHits = collector.getIndexHits( null );
    assertEquals( 2, indexHits.size() );
    assertEquals( "1", indexHits.next().get( "id" ) );
    assertEquals( "2", indexHits.next().get( "id" ) );
    assertFalse( indexHits.hasNext() );
}
项目:neo4j-lucene5-index    文件:DocValuesCollectorTest.java   
@Test
public void shouldReturnEmptyIteratorWhenNoHits() throws Exception
{
    // given
    DocValuesCollector collector = new DocValuesCollector( false );
    IndexReaderStub readerStub = indexReaderWithMaxDocs( 42 );

    // when
    collector.doSetNextReader( readerStub.getContext() );

    // then
    IndexHits<Document> indexHits = collector.getIndexHits( null );
    assertEquals( 0, indexHits.size() );
    assertEquals( Float.NaN, indexHits.currentScore(), 0.0f );
    assertFalse( indexHits.hasNext() );
}
项目:neo4art    文件:ArtworkBatchInserterRepository.java   
/**
 * @see org.neo4art.core.repository.ArtworkRepository#getArtworkByTitle(java.lang.String)
 */
@Override
public Long getArtworkByTitle(String title)
{
  Long nodeId = null;

  IndexHits<Long> indexHits = Neo4ArtBatchInserterSingleton.getFromLegacyNodeIndex(CoreLegacyIndex.ARTWORK_LEGACY_INDEX, "title", title);

  if (indexHits.hasNext())
  {
    nodeId = indexHits.next();
  }

  indexHits.close();

  return nodeId;
}
项目:neo4art    文件:ColourBatchInserterRepository.java   
/**
 * 
 * @param colourAnalysisNodeId
 * @param closestColour
 * @param colourRelationship
 */
private void connectColourAnalysisToClosestColour(Long colourAnalysisNodeId, Colour closestColour, ColourRelationship colourRelationship)
{
  if (closestColour != null)
  {
    IndexHits<Long> closestColourIndexHits = Neo4ArtBatchInserterSingleton.getFromLegacyNodeIndex(ColourLegacyIndex.COLOUR_LEGACY_INDEX, Colour.RGB_PROPERTY_NAME, closestColour.getColor().getRGB());

    if (closestColourIndexHits != null)
    {
      if (closestColourIndexHits.hasNext())
      {
        long closestColourIndexHit = closestColourIndexHits.next();

        Neo4ArtBatchInserterSingleton.createRelationship(colourAnalysisNodeId, closestColourIndexHit, colourRelationship, null);
      }
    }

    closestColourIndexHits.close();
  }
}
项目:SciGraph    文件:VocabularyNeo4jImpl.java   
List<Concept> limitHits(IndexHits<Node> hits, Query query) {
  try (Transaction tx = graph.beginTx()) {
    Iterable<Concept> concepts = Iterables.transform(hits, transformer);
    if (!query.isIncludeDeprecated()) {
      concepts = filter(concepts, new Predicate<Concept>() {
        @Override
        public boolean apply(Concept concept) {
          return !concept.isDeprecated();
        }
      });
    }
    Iterable<Concept> limitedHits = limit(concepts, query.getLimit());
    List<Concept> ret = newArrayList(limitedHits);
    tx.success();
    return ret;
  }
}
项目:octotron_core    文件:Neo4jIndex.java   
@Override
public Info<EGraphType> GetObject(String name, Object value)
{
    ReadableIndex<Node> node_auto_index = graph.GetInnerIndex()
        .getNodeAutoIndexer().getAutoIndex();

    IndexHits<Node> iterator
        = node_auto_index.get(name, value);

    if(!iterator.hasNext())
        throw new ExceptionModelFail
            ("element not found " + name + " with value " + value);

    Info<EGraphType> obj_uid = new Info<>(iterator.next().getId(), EGraphType.OBJECT);

    if(iterator.hasNext())
        throw new ExceptionModelFail
            ("more than one element match the criteria: " + name + " " + value.toString());

    return obj_uid;
}
项目:octotron_core    文件:Neo4jIndex.java   
@Override
public Info<EGraphType> GetLink(String name, Object value)
{
    ReadableIndex<Relationship> rel_auto_index = graph.GetInnerIndex()
        .getRelationshipAutoIndexer().getAutoIndex();

    IndexHits<Relationship> iterator
        = rel_auto_index.get(name, value);

    if(!iterator.hasNext())
        throw new ExceptionModelFail
            ("element not found" + name);

    Info<EGraphType> link_uid = new Info<>(iterator.next().getId(), EGraphType.LINK);

    if(iterator.hasNext())
        throw new ExceptionModelFail
            ("more than one element match the criteria: " + name + " " + value.toString());

    return link_uid;
}
项目:neo4j-mobile-android    文件:LuceneIndex.java   
private IndexHits<T> newEntityIterator( IndexHits<Long> idIterator )
{
    return new IdToEntityIterator<T>( idIterator )
    {
        @Override
        protected T underlyingObjectToObject( Long id )
        {
            return getById( id );
        }

        @Override
        protected void itemDodged( Long item )
        {
            abandonedIds.add( item );
        }
    };
}
项目:neo4j-mobile-android    文件:DbWrapper.java   
@Override
public INodeIterator getNodesFromIndex(String name, String key, ParcelableIndexValue value, ParcelableError err)
        throws RemoteException {
    try {
        resumeTrxIfExists();
        try {
            Index<Node> nodeIndex = mDb.index().forNodes(name);
            IndexHits<Node> hits = nodeIndex.get(key, value.get());
            return new NodeIteratorWrapper(hits.iterator());
        } finally {
            suspendCurrentTrx("getNodesFromIndex");
        }
    } catch (Exception e) {
        Log.e(TAG, "Failed to remove node from index '" + name + "'", e);
        err.setError(Errors.TRANSACTION, e.getMessage());
        return null;
    }
}
项目:neo4j-mobile-android    文件:DbWrapper.java   
@Override
public IRelationshipIterator getRelationshipsFromIndex(String name, String key, ParcelableIndexValue value, ParcelableError err)
        throws RemoteException {

    try {
        resumeTrxIfExists();

        try {
            RelationshipIndex index = mDb.index().forRelationships(name); // this
                                                                          // will
                                                                          // create
                                                                          // the
                                                                          // index
            IndexHits<Relationship> hits = index.get(key, value.get());
            return new RelationshipIteratorWrapper(hits);
        } finally {
            suspendCurrentTrx("getRelationshipsFromIndex");
        }
    } catch (Exception e) {
        Log.e(TAG, "Failed to add relationship to index '" + name + "'", e);
        err.setError(Errors.TRANSACTION, e.getMessage());
        return null;
    }
}
项目:timbuctoo    文件:Database.java   
private Optional<Vertex> findVertexInRdfIndex(String indexName, String nodeUri) {
  IndexHits<org.neo4j.graphdb.Node> rdfurls = rdfIndex.get(indexName, nodeUri);
  if (rdfurls.hasNext()) {
    long vertexId = rdfurls.next().getId();
    if (rdfurls.hasNext()) {
      StringBuilder errorMessage = new StringBuilder().append("There is more then one node in ")
                                                      .append(indexName)
                                                      .append(" for the rdfUrl ")
                                                      .append(nodeUri)
                                                      .append(" ")
                                                      .append("namely ")
                                                      .append(vertexId);
      rdfurls.forEachRemaining(x -> errorMessage.append(", ").append(x.getId()));
      LOG.error(errorMessage.toString());
    }
    GraphTraversal<Vertex, Vertex> vertexLookup = traversal().V(vertexId);
    if (vertexLookup.hasNext()) {
      Vertex vertex = vertexLookup.next();
      return Optional.of(vertex);
    } else {
      LOG.error("Index returned a Node for " + indexName + " - " + nodeUri + " but the node id " + vertexId +
        "could not be found using Tinkerpop.");
    }
  }
  return Optional.empty();
}
项目:EvilCoder    文件:Traversals.java   
public static IndexHits<Node> getStatementsForFunction(Node funcNode)
{
    String query = String.format("%s:True AND %s:%d", NodeKeys.IS_CFG_NODE,
            NodeKeys.FUNCTION_ID, funcNode.getId());

    return Neo4JDBInterface.queryIndex(query);
}
项目:neo4j-talend-component    文件:Neo4jBatchDatabase.java   
/**
 * Find a node in the index.
 *
 * @param indexName Name of the batch index
 * @param value     Value to search in index
 * @return Neo4j node identifier
 */
public Long findNodeInBatchIndex(String indexName, Object value) {
    Long nodeId = null;
    if (this.batchInserterIndexes.containsKey(indexName)) {
        IndexHits<Long> result = this.batchInserterIndexes.get(indexName).get(BACTH_INDEX_ID_NAME, value);
        if (result.size() > 0) {
            nodeId = result.getSingle();
        }
    } else {
        log.trace("Can't find object [" + value + "] into index " + indexName);
    }
    return nodeId;
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:PosSearch.java   
@GET
@Path("/tags/{label}")
public Response getPosTagByLabel(@PathParam("label") final String label)
{
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction ignored = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> postags = index.forNodes("PosTag");
                IndexHits<Node> hits = postags.get( "label", label );
                Node postag = hits.getSingle();
                jg.writeStartObject();
                for (String field : postag.getPropertyKeys()) {
                    Object value = postag.getProperty(field);
                    if (field.contains("_count") && value instanceof Integer)
                        jg.writeNumberField(field, (Integer) value);
                    else if (field.contains("_count") && value instanceof Long)
                        jg.writeNumberField(field, (Long) value);
                    else
                        jg.writeStringField(field, (String) postag.getProperty(field));
                }
                jg.writeEndObject();
                jg.flush();
                jg.close();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:WhiteLab2.0-Neo4J-Plugin    文件:PosSearch.java   
@GET
@Path("/heads/{label}")
public Response getPosHeadByLabel(@PathParam("label") final String label)
{
    StreamingOutput stream = new StreamingOutput()
    {
        @Override
        public void write( OutputStream os ) throws IOException, WebApplicationException
        {
            try ( Transaction ignored = database.beginTx() ) {
                JsonGenerator jg = objectMapper.getFactory().createGenerator(os, JsonEncoding.UTF8);
                IndexManager index = database.index();
                Index<Node> postags = index.forNodes("PosHead");
                IndexHits<Node> hits = postags.get( "label", label );
                Node poshead = hits.getSingle();
                jg.writeStartObject();
                for (String field : poshead.getPropertyKeys()) {
                    Object value = poshead.getProperty(field);
                    if (field.contains("_count") && value instanceof Integer)
                        jg.writeNumberField(field, (Integer) value);
                    else if (field.contains("_count") && value instanceof Long)
                        jg.writeNumberField(field, (Long) value);
                    else
                        jg.writeStringField(field, (String) poshead.getProperty(field));
                }
                jg.writeEndObject();
                jg.flush();
                jg.close();
            }
        }
    };

    return Response.ok().entity( stream ).type( MediaType.APPLICATION_JSON ).build();
}
项目:neo4j-lucene5-index    文件:LuceneIndex.java   
private IndexHits<Document> search( IndexReference searcherRef, IndexSearcher fulltextTransactionStateSearcher,
        Query query, QueryContext additionalParametersOrNull, Collection<EntityId> removed ) throws IOException
{
    if ( fulltextTransactionStateSearcher != null && !removed.isEmpty() )
    {
        letThroughAdditions( fulltextTransactionStateSearcher, query, removed );
    }

    IndexSearcher searcher = fulltextTransactionStateSearcher == null ? searcherRef.getSearcher() :
            new IndexSearcher( new MultiReader( searcherRef.getSearcher().getIndexReader(),
                    fulltextTransactionStateSearcher.getIndexReader() ) );
    IndexHits<Document> result;
    if ( additionalParametersOrNull != null && additionalParametersOrNull.getTop() > 0 )
    {
        result = new TopDocsIterator( query, additionalParametersOrNull, searcher );
    }
    else
    {
        Sort sorting = additionalParametersOrNull != null ?
                additionalParametersOrNull.getSorting() : null;
        boolean forceScore = additionalParametersOrNull == null ||
                !additionalParametersOrNull.getTradeCorrectnessForSpeed();
        DocValuesCollector collector = new DocValuesCollector( forceScore );
        searcher.search( query, collector );
        return collector.getIndexHits( sorting );
    }
    return result;
}
项目:neo4j-lucene5-index    文件:DocToIdIterator.java   
public DocToIdIterator( IndexHits<Document> source, Collection<EntityId> exclude, IndexReference searcherOrNull,
        PrimitiveLongSet idsModifiedInTransactionState )
{
    this.source = source;
    this.removedInTransactionState = exclude;
    this.searcherOrNull = searcherOrNull;
    this.idsModifiedInTransactionState = idsModifiedInTransactionState;
    if ( source.size() == 0 )
    {
        close();
    }
}
项目:neo4j-lucene5-index    文件:DocValuesCollector.java   
/**
 * Replay the search and collect every hit into TopDocs. One {@code ScoreDoc} is allocated
 * for every hit and the {@code Document} instance is loaded lazily with on every iteration step.
 *
 * @param sort how to sort the iterator. If this is null, results will be in index-order.
 * @return an indexhits iterator over all matches
 * @throws IOException
 */
public IndexHits<Document> getIndexHits( Sort sort ) throws IOException
{
    List<MatchingDocs> matchingDocs = getMatchingDocs();
    int size = getTotalHits();
    if ( size == 0 )
    {
        return new AbstractIndexHits<Document>()
        {
            @Override
            public int size()
            {
                return 0;
            }

            @Override
            public float currentScore()
            {
                return Float.NaN;
            }

            @Override
            protected Document fetchNextOrNull()
            {
                return null;
            }
        };
    }

    if ( sort == null || sort == Sort.INDEXORDER )
    {
        return new DocsInIndexOrderIterator( matchingDocs, size, isKeepScores() );
    }

    TopDocs topDocs = getTopDocs( sort, size );
    LeafReaderContext[] contexts = getLeafReaderContexts( matchingDocs );
    return new TopDocsIterator( topDocs, contexts );
}
项目:neo4j-lucene5-index    文件:ImdbDocTest.java   
@Test
public void doGetForNodes()
{
    Index<Node> actors = graphDb.index().forNodes( "actors" );

    // START SNIPPET: getSingleNode
    IndexHits<Node> hits = actors.get( "name", "Keanu Reeves" );
    Node reeves = hits.getSingle();
    // END SNIPPET: getSingleNode

    assertEquals( "Keanu Reeves", reeves.getProperty( "name" ) );
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void indexHitsFromQueryingRemovedDoesNotReturnNegativeCount()
{
    Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG );
    Node theNode = graphDb.createNode();
    index.remove( theNode );
    IndexHits<Node> hits = index.query( "someRandomKey", theNode.getId() );
    assertTrue( hits.size() >= 0 );
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void testSortByRelevance()
{
    Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG );

    Node node1 = graphDb.createNode();
    Node node2 = graphDb.createNode();
    Node node3 = graphDb.createNode();
    index.add( node1, "name", "something" );
    index.add( node2, "name", "something" );
    index.add( node2, "foo", "yes" );
    index.add( node3, "name", "something" );
    index.add( node3, "foo", "yes" );
    index.add( node3, "bar", "yes" );
    restartTx();

    IndexHits<Node> hits = index.query(
            new QueryContext( "+name:something foo:yes bar:yes" ).sort( Sort.RELEVANCE ) );
    assertEquals( node3, hits.next() );
    assertEquals( node2, hits.next() );
    assertEquals( node1, hits.next() );
    assertFalse( hits.hasNext() );
    index.delete();
    node1.delete();
    node2.delete();
    node3.delete();
}
项目:neo4j-lucene5-index    文件:TestLuceneIndex.java   
@Test
public void testNumericValueArrays()
{
    Index<Node> index = nodeIndex( LuceneIndexImplementation.EXACT_CONFIG );

    Node node1 = graphDb.createNode();
    index.add( node1, "number", new ValueContext[]{ numeric( 45 ), numeric( 98 ) } );
    Node node2 = graphDb.createNode();
    index.add( node2, "number", new ValueContext[]{ numeric( 47 ), numeric( 100 ) } );


    IndexHits<Node> indexResult1 = index.query( "number", newIntRange( "number", 47, 98, true, true ) );
    assertThat( indexResult1, contains( node1, node2 ) );
    assertThat( indexResult1.size(), is( 2 ));

    IndexHits<Node> indexResult2 = index.query( "number", newIntRange( "number", 44, 46, true, true ) );
    assertThat( indexResult2, contains( node1 ) );
    assertThat( indexResult2.size(), is( 1 ) );

    IndexHits<Node> indexResult3 = index.query( "number", newIntRange( "number", 99, 101, true, true ) );
    assertThat( indexResult3, contains( node2 ) );
    assertThat( indexResult3.size(), is( 1 ) );

    IndexHits<Node> indexResult4 = index.query( "number", newIntRange( "number", 47, 98, false, false ) );
    assertThat( indexResult4, isEmpty() );

    IndexHits<Node> indexResult5 = index.query( "number", numericRange( "number", null, 98, true, true ) );
    assertContains( indexResult5, node1, node2 );

    IndexHits<Node> indexResult6 = index.query( "number", numericRange( "number", 47, null, true, true ) );
    assertContains( indexResult6, node1, node2 );
}
项目:neo4j-lucene5-index    文件:MandatoryTransactionsForIndexHitsFacadeTests.java   
private IndexHits<Node> queryIndex( Index<Node> index )
{
    GraphDatabaseService graphDatabaseService = dbRule.getGraphDatabaseService();
    try ( Transaction transaction = graphDatabaseService.beginTx() )
    {
        return index.get( "foo", 42 );
    }
}
项目:neo4art    文件:Neo4ArtBatchInserterSingleton.java   
/**
 * TODO it's not necessary to provide key and value: we could also just pass a Node 'cause we already know the key (defined at index creation time) 
 * 
 * @param indexName
 * @param key
 * @param value
 * @return
 */
public static IndexHits<Long> getFromLegacyNodeIndex(Neo4ArtLegacyIndex neo4ArtLegacyIndex, String key, Object value)
{
  BatchInserterIndex batchInserterIndex = getBatchInserterIndexProviderInstance().nodeIndex(neo4ArtLegacyIndex.getName(), getLegacyNodeIndexConfig(neo4ArtLegacyIndex.getType()));

  if (batchInserterIndex == null)
  {
    throw new IllegalArgumentException("Index " + neo4ArtLegacyIndex.getName() + " doesn't exists. You must create it before getting something from it.");
  }    

  return batchInserterIndex.get(key, value);
}
项目:neo4art    文件:DictionaryServiceTest.java   
@Test
@Ignore
public void shouldSaveDictionary()
{
  try
  {
    FileUtils.deleteDirectory(new File(Neo4ArtGraphDatabase.NEO4J_STORE_DIR));

    DictionaryService dictionaryService = new DictionaryBasicService(Locale.ENGLISH);

    dictionaryService.createLegacyIndexes();
    dictionaryService.saveDictionary();

    IndexHits<Long> indexHits = Neo4ArtBatchInserterSingleton.getFromLegacyNodeIndex(NLPLegacyIndex.WORD_LEGACY_INDEX, "word", "art");

    Assert.assertEquals(1, indexHits.size());
    Assert.assertTrue(indexHits.getSingle() > 0);

    indexHits.close();
  }
  catch (Exception e)
  {
    e.printStackTrace();

    Assert.fail(e.getMessage());
  }
  finally
  {
    Neo4ArtBatchInserterSingleton.shutdownBatchInserterInstance();
  }
}
项目:neo4art    文件:NLPIndexManagerTest.java   
@Test
public void shouldRetrieveNodeFromIndex()
{
  try
  {
    FileUtils.deleteDirectory(new File(Neo4ArtGraphDatabase.NEO4J_STORE_DIR));

    Word word = new Word("neo4art", null, null);

    long neo4artNodeId = Neo4ArtBatchInserterSingleton.createNode(word);

    Neo4ArtBatchInserterSingleton.createLegacyNodeIndex(NLPLegacyIndex.WORD_LEGACY_INDEX);
    Neo4ArtBatchInserterSingleton.addToLegacyNodeIndex(NLPLegacyIndex.WORD_LEGACY_INDEX, word);
    Neo4ArtBatchInserterSingleton.flushLegacyNodeIndex(NLPLegacyIndex.WORD_LEGACY_INDEX);

    IndexHits<Long> indexHits = Neo4ArtBatchInserterSingleton.getFromLegacyNodeIndex(NLPLegacyIndex.WORD_LEGACY_INDEX, "word", "neo4art");

    Assert.assertEquals(1, indexHits.size());
    Assert.assertEquals(neo4artNodeId, indexHits.getSingle().longValue());
  }
  catch (Exception e)
  {
    e.printStackTrace();

    Assert.fail(e.getMessage());
  }
  finally
  {
    Neo4ArtBatchInserterSingleton.shutdownBatchInserterInstance();
  }
}
项目:mondo-hawk    文件:Neo4JIterable.java   
@Override
public int size() {
    try {
        Iterable<?> iterable = query.call();
        if (iterable instanceof IndexHits<?>) {
            return ((IndexHits<?>) iterable).size();
        } else {
            return count(iterable);
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return 0;
    }
}
项目:SciGraph    文件:VocabularyNeo4jImpl.java   
@Override
public List<Concept> searchConcepts(Query query) {
  QueryParser parser = getQueryParser();
  // BooleanQuery finalQuery = new BooleanQuery();
  Builder finalQueryBuilder = new BooleanQuery.Builder();
  try {
    if (query.isIncludeSynonyms() || query.isIncludeAbbreviations() || query.isIncludeAcronyms()) {
      // BooleanQuery subQuery = new BooleanQuery();
      Builder subQueryBuilder = new BooleanQuery.Builder();
      subQueryBuilder.add(LuceneUtils.getBoostedQuery(parser, query.getInput(), 10.0f),
          Occur.SHOULD);
      String escapedQuery = QueryParser.escape(query.getInput());
      if (query.isIncludeSynonyms()) {
        subQueryBuilder.add(parser.parse(Concept.SYNONYM + ":" + escapedQuery), Occur.SHOULD);
      }
      if (query.isIncludeAbbreviations()) {
        subQueryBuilder.add(parser.parse(Concept.ABREVIATION + ":" + escapedQuery), Occur.SHOULD);
      }
      if (query.isIncludeAcronyms()) {
        subQueryBuilder.add(parser.parse(Concept.ACRONYM + ":" + escapedQuery), Occur.SHOULD);
      }
      finalQueryBuilder.add(subQueryBuilder.build(), Occur.MUST);
    } else {
      finalQueryBuilder.add(parser.parse(query.getInput()), Occur.MUST);
    }
  } catch (ParseException e) {
    logger.log(Level.WARNING, "Failed to parse query", e);
  }
  addCommonConstraints(finalQueryBuilder, query);
  IndexHits<Node> hits = null;
  BooleanQuery finalQuery = finalQueryBuilder.build();

  try (Transaction tx = graph.beginTx()) {
    hits = graph.index().getNodeAutoIndexer().getAutoIndex().query(finalQuery);
    tx.success();
  }
  return limitHits(hits, query);
}