Search in sources :

Example 86 with Filter

use of org.neo4j.ogm.cypher.Filter in project framework by dynamiatools.

the class Neo4jCrudService method buildFilters.

private Filters buildFilters(QueryParameters params) {
    Filters filters = new Filters();
    params.forEach((k, v) -> {
        if (v instanceof QueryCondition) {
            Filter filter = new Filter(k, Neo4jQueryCondition.getOperator((QueryCondition) v), ((QueryCondition) v).getValue());
            filter.setBooleanOperator(BooleanOperator.AND);
            filters.add(filter);
        } else {
            Filter filter = new Filter(k, ComparisonOperator.EQUALS, v);
            filter.setBooleanOperator(BooleanOperator.AND);
            filters.add(filter);
        }
    });
    return filters;
}
Also used : Filters(org.neo4j.ogm.cypher.Filters) Filter(org.neo4j.ogm.cypher.Filter)

Example 87 with Filter

use of org.neo4j.ogm.cypher.Filter in project neo4j-ogm by neo4j.

the class FilteredQueryBuilder method constructRelationshipQuery.

private static StringBuilder constructRelationshipQuery(String type, Iterable<Filter> filters, Map<String, Object> properties) {
    // Filters are created in 3 steps: For deep nested filter, the improved version
    // NodeQueryBuilder is used. For the others the old approach still applies.
    FiltersAtStartNode outgoingDeepNestedFilters = new FiltersAtStartNode();
    FiltersAtStartNode incomingDeepNestedFilters = new FiltersAtStartNode();
    FiltersAtStartNode outgoingFilters = new FiltersAtStartNode();
    FiltersAtStartNode incomingFilters = new FiltersAtStartNode();
    List<Filter> relationshipFilters = new ArrayList<>();
    Direction initialDirection = null;
    for (Filter filter : filters) {
        if (filter.isNested() || filter.isDeepNested()) {
            if (filter.isDeepNested()) {
                List<Filter.NestedPathSegment> nestedPath = filter.getNestedPath();
                Filter.NestedPathSegment firstNestedPathSegment = nestedPath.get(0);
                filter.setOwnerEntityType(firstNestedPathSegment.getPropertyType());
                FiltersAtStartNode target;
                if (Relationship.Direction.OUTGOING == firstNestedPathSegment.getRelationshipDirection()) {
                    target = outgoingDeepNestedFilters;
                } else {
                    target = incomingDeepNestedFilters;
                }
                Filter.NestedPathSegment[] newPath = new Filter.NestedPathSegment[nestedPath.size() - 1];
                if (nestedPath.size() > 1) {
                    // The first element will represent the owning entity, so we need to get rid of it.
                    nestedPath.subList(1, nestedPath.size()).toArray(newPath);
                } else {
                    // The list of deep nested filters need an anchor only for relationships with one
                    // nested segments.
                    target.startNodeLabel = firstNestedPathSegment.getNestedEntityTypeLabel();
                }
                filter.setNestedPath(newPath);
                target.content.add(filter);
                if (initialDirection == null) {
                    initialDirection = firstNestedPathSegment.getRelationshipDirection();
                }
            } else {
                FiltersAtStartNode target;
                Direction relationshipDirection = filter.getRelationshipDirection();
                if (Relationship.OUTGOING == relationshipDirection) {
                    target = outgoingFilters;
                } else {
                    target = incomingFilters;
                }
                if (initialDirection == null) {
                    initialDirection = filter.getRelationshipDirection();
                }
                addFilterToList(target, filter);
            }
        } else {
            if (relationshipFilters.size() == 0) {
                filter.setBooleanOperator(BooleanOperator.NONE);
            } else {
                if (filter.getBooleanOperator().equals(BooleanOperator.NONE)) {
                    throw new MissingOperatorException("BooleanOperator missing for filter with property name " + filter.getPropertyName());
                }
            }
            relationshipFilters.add(filter);
        }
    }
    StringBuilder query = new StringBuilder();
    boolean outgoingDeepNested = !outgoingDeepNestedFilters.content.isEmpty();
    if (outgoingDeepNested) {
        NodeQueryBuilder nqb = new NodeQueryBuilder(outgoingDeepNestedFilters.startNodeLabel, outgoingDeepNestedFilters.content, "n");
        FilteredQuery filteredQuery = nqb.build();
        query.append(filteredQuery.statement()).append(" ");
        properties.putAll(filteredQuery.parameters());
    }
    if (!incomingDeepNestedFilters.content.isEmpty()) {
        NodeQueryBuilder nqb = new NodeQueryBuilder(incomingDeepNestedFilters.startNodeLabel, incomingDeepNestedFilters.content, outgoingDeepNested ? "m" : "n");
        FilteredQuery filteredQuery = nqb.build();
        query.append(filteredQuery.statement()).append(" ");
        if (outgoingDeepNested) {
            query.append(", n ");
        }
        properties.putAll(filteredQuery.parameters());
    }
    createNodeMatchSubquery(properties, outgoingFilters, query, "n");
    createNodeMatchSubquery(properties, incomingFilters, query, "m");
    createRelationSubquery(type, properties, relationshipFilters, query, initialDirection);
    return query;
}
Also used : ArrayList(java.util.ArrayList) Direction(org.neo4j.ogm.annotation.Relationship.Direction) MissingOperatorException(org.neo4j.ogm.exception.core.MissingOperatorException) Filter(org.neo4j.ogm.cypher.Filter)

Example 88 with Filter

use of org.neo4j.ogm.cypher.Filter in project neo4j-ogm by neo4j.

the class FilteredQueryBuilder method appendFilters.

private static void appendFilters(List<Filter> filters, String nodeIdentifier, StringBuilder query, Map<String, Object> properties) {
    for (Filter filter : filters) {
        query.append(filter.toCypher(nodeIdentifier, false));
        properties.putAll(filter.parameters());
    }
}
Also used : Filter(org.neo4j.ogm.cypher.Filter)

Example 89 with Filter

use of org.neo4j.ogm.cypher.Filter in project neo4j-ogm by neo4j.

the class SessionDelegate method resolvePropertyAnnotations.

void resolvePropertyAnnotations(Class entityType, Iterable<Filter> filters) {
    for (Filter filter : filters) {
        if (filter.getOwnerEntityType() == null) {
            filter.setOwnerEntityType(entityType);
        }
        String propertyName = resolvePropertyName(filter.getOwnerEntityType(), filter.getPropertyName());
        Filter.setNameFromProperty(filter, propertyName);
        ClassInfo classInfo = session.metaData().classInfo(entityType.getName());
        FieldInfo fieldInfo = classInfo.getFieldInfo(filter.getPropertyName());
        if (fieldInfo != null) {
            filter.setPropertyConverter(fieldInfo.getPropertyConverter());
        }
        if (filter.isNested()) {
            resolveRelationshipType(filter);
            ClassInfo nestedClassInfo = session.metaData().classInfo(filter.getNestedPropertyType().getName());
            filter.setNestedEntityTypeLabel(session.metaData().entityType(nestedClassInfo.name()));
            if (session.metaData().isRelationshipEntity(nestedClassInfo.name())) {
                filter.setNestedRelationshipEntity(true);
            }
        } else if (filter.isDeepNested()) {
            Class parentOwnerType = filter.getOwnerEntityType();
            for (Filter.NestedPathSegment nestedPathSegment : filter.getNestedPath()) {
                resolveRelationshipType(parentOwnerType, nestedPathSegment);
                ClassInfo nestedClassInfo = session.metaData().classInfo(nestedPathSegment.getPropertyType().getName());
                nestedPathSegment.setNestedEntityTypeLabel(session.metaData().entityType(nestedClassInfo.name()));
                if (session.metaData().isRelationshipEntity(nestedClassInfo.name())) {
                    nestedPathSegment.setNestedRelationshipEntity(true);
                }
                parentOwnerType = nestedPathSegment.getPropertyType();
            }
        }
    }
}
Also used : Filter(org.neo4j.ogm.cypher.Filter) FieldInfo(org.neo4j.ogm.metadata.FieldInfo) ClassInfo(org.neo4j.ogm.metadata.ClassInfo)

Example 90 with Filter

use of org.neo4j.ogm.cypher.Filter in project neo4j-ogm by neo4j.

the class DeleteDelegate method deleteOneOrMoreObjects.

// TODO : this is being done in multiple requests at the moment, one per object. Why not put them in a single request?
private void deleteOneOrMoreObjects(List<?> objects, Set<Object> neighbours) {
    Set<Object> notified = new HashSet<>();
    if (session.eventsEnabled()) {
        for (Object affectedObject : neighbours) {
            if (!notified.contains(affectedObject)) {
                session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.PRE_SAVE));
                notified.add(affectedObject);
            }
        }
    }
    for (Object object : objects) {
        MetaData metaData = session.metaData();
        ClassInfo classInfo = metaData.classInfo(object);
        if (classInfo == null) {
            session.warn(object.getClass().getName() + " is not an instance of a persistable class");
        } else {
            MappingContext mappingContext = session.context();
            Long id = mappingContext.optionalNativeId(object).filter(possibleId -> possibleId >= 0).orElseGet(() -> {
                session.warn(String.format("Instance of class %s has to be reloaded to be deleted. This can happen if the session has " + "been cleared between loading and deleting or using an object from a different transaction.", object.getClass()));
                return classInfo.getPrimaryIndexOrIdReader().apply(object).map(primaryIndexOrId -> session.load(object.getClass(), (Serializable) primaryIndexOrId)).flatMap(reloadedObject -> mappingContext.optionalNativeId(reloadedObject)).orElse(-1L);
            });
            if (id >= 0) {
                Statement request = getDeleteStatement(object, id, classInfo);
                if (session.eventsEnabled() && !notified.contains(object)) {
                    session.notifyListeners(new PersistenceEvent(object, Event.TYPE.PRE_DELETE));
                    notified.add(object);
                }
                RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters());
                session.doInTransaction(() -> {
                    try (Response<RowModel> response = session.requestHandler().execute(query)) {
                        if (request.optimisticLockingConfig().isPresent()) {
                            List<RowModel> rowModels = response.toList();
                            session.optimisticLockingChecker().checkResultsCount(rowModels, request);
                        }
                        if (metaData.isRelationshipEntity(classInfo.name())) {
                            session.detachRelationshipEntity(id);
                        } else {
                            session.detachNodeEntity(id);
                        }
                        // enabled in the first place.
                        if (notified.contains(object)) {
                            session.notifyListeners(new PersistenceEvent(object, Event.TYPE.POST_DELETE));
                        }
                    }
                }, Transaction.Type.READ_WRITE);
            }
        }
    }
    if (session.eventsEnabled()) {
        for (Object affectedObject : neighbours) {
            if (notified.contains(affectedObject)) {
                session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.POST_SAVE));
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) CypherQuery(org.neo4j.ogm.cypher.query.CypherQuery) Response(org.neo4j.ogm.response.Response) Neo4jSession(org.neo4j.ogm.session.Neo4jSession) MappingContext(org.neo4j.ogm.context.MappingContext) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) RelationshipDeleteStatements(org.neo4j.ogm.session.request.strategy.impl.RelationshipDeleteStatements) ArrayList(java.util.ArrayList) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) HashSet(java.util.HashSet) RowModel(org.neo4j.ogm.model.RowModel) Map(java.util.Map) Event(org.neo4j.ogm.session.event.Event) Transaction(org.neo4j.ogm.transaction.Transaction) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) Result(org.neo4j.ogm.model.Result) DeleteStatements(org.neo4j.ogm.session.request.strategy.DeleteStatements) MetaData(org.neo4j.ogm.metadata.MetaData) Set(java.util.Set) NodeDeleteStatements(org.neo4j.ogm.session.request.strategy.impl.NodeDeleteStatements) Filter(org.neo4j.ogm.cypher.Filter) Statement(org.neo4j.ogm.request.Statement) Serializable(java.io.Serializable) List(java.util.List) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) Collections(java.util.Collections) Serializable(java.io.Serializable) Statement(org.neo4j.ogm.request.Statement) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) MappingContext(org.neo4j.ogm.context.MappingContext) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) MetaData(org.neo4j.ogm.metadata.MetaData) RowModel(org.neo4j.ogm.model.RowModel) HashSet(java.util.HashSet) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest)

Aggregations

Filter (org.neo4j.ogm.cypher.Filter)155 Test (org.junit.Test)146 Filters (org.neo4j.ogm.cypher.Filters)78 User (org.neo4j.ogm.domain.cineasts.annotated.User)19 Rating (org.neo4j.ogm.domain.cineasts.annotated.Rating)18 Movie (org.neo4j.ogm.domain.cineasts.annotated.Movie)17 Restaurant (org.neo4j.ogm.domain.restaurant.Restaurant)12 Date (java.util.Date)10 Session (org.neo4j.ogm.session.Session)10 DistanceFromNativePoint (org.neo4j.ogm.cypher.function.DistanceFromNativePoint)8 SomethingSpatial (org.neo4j.ogm.persistence.types.nativetypes.SomethingSpatial)8 HashSet (java.util.HashSet)7 CypherQuery (org.neo4j.ogm.cypher.query.CypherQuery)7 GroupMember (org.neo4j.ogm.domain.gh824.GroupMember)7 ArrayList (java.util.ArrayList)4 Actor (org.neo4j.ogm.domain.cineasts.annotated.Actor)4 User (org.neo4j.ogm.domain.gh824.User)4 UserGroup (org.neo4j.ogm.domain.gh824.UserGroup)4 Studio (org.neo4j.ogm.domain.music.Studio)4 Collections (java.util.Collections)2