1

I have the following neo4j models with a Document and Text relationship, where multiple texts are linked to a document :

class Document(StructuredNode):
    """Document Neo4J model for documents"""
    document_id = IntegerProperty(required = True)


class Text(StructuredNode):
    """Text model for managing texts"""

    # Inherent text properties
    text_id = IntegerProperty(required = True)
    text = StringProperty(required = True)

    document = RelationshipTo('Document', "PARENT")

In order to fetch ALL the Text objects linked with a specific document, I am using traversal as follows :

def get_all_texts_by_document_id(document_id):
    document = Document.nodes.get_or_none(document_id = document_id)
    definition = dict(node_class = Text, direction = EITHER, relation_type = "PARENT", model = None)
    document_to_text_traversal = Traversal(document, Text.__label__, definition)
    texts = document_to_text_traversal.all()
    print(f"Returning {len(texts)} texts for document_id {document_id}")
    return texts

I want to fetch a text with specific text ID and currently I am iterating with an if condition over the list of all the texts received using the above function.

Is there an inbuilt method / better way to filter on the basis of text_id once the traversal is done ?

Anshuman Tiwari
  • 424
  • 9
  • 19

1 Answers1

2

I am not aware of any way to filter nodes after traversal with neomodel.

However, if you do not have to use Traversal objects, you could use something like this:

  • add the relationship from Text to Document by adding this line to your Document class:

    texts = RelationshipFrom('Text', "PARENT")
    
  • Follow the PARENT relationship and filter on the end nodes:

    document = Document.nodes.get_or_none(document_id=1)
    if document:
        texts = document.texts.filter(text_id=1)
        print(texts.all())
    
stellasia
  • 5,372
  • 4
  • 23
  • 43