idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
33,200
public Optional < ExclusiveEdge > popBestEdge ( Node component , Arborescence < Node > best ) { if ( ! queueByDestination . containsKey ( component ) ) return Optional . empty ( ) ; return queueByDestination . get ( component ) . popBestEdge ( best ) ; }
Always breaks ties in favor of edges in best
33,201
public static Set < Fragment > inferRelationTypes ( TransactionOLTP tx , Set < Fragment > allFragments ) { Set < Fragment > inferredFragments = new HashSet < > ( ) ; Map < Variable , Type > labelVarTypeMap = getLabelVarTypeMap ( tx , allFragments ) ; if ( labelVarTypeMap . isEmpty ( ) ) return inferredFragments ; Multimap < Variable , Type > instanceVarTypeMap = getInstanceVarTypeMap ( allFragments , labelVarTypeMap ) ; Multimap < Variable , Variable > relationRolePlayerMap = getRelationRolePlayerMap ( allFragments , instanceVarTypeMap ) ; if ( relationRolePlayerMap . isEmpty ( ) ) return inferredFragments ; Multimap < Type , RelationType > relationMap = HashMultimap . create ( ) ; labelVarTypeMap . values ( ) . stream ( ) . distinct ( ) . forEach ( type -> addAllPossibleRelations ( relationMap , type ) ) ; Map < Label , Statement > inferredLabels = new HashMap < > ( ) ; relationRolePlayerMap . asMap ( ) . forEach ( ( relationVar , rolePlayerVars ) -> { Set < Type > possibleRelationTypes = rolePlayerVars . stream ( ) . filter ( instanceVarTypeMap :: containsKey ) . map ( rolePlayer -> getAllPossibleRelationTypes ( instanceVarTypeMap . get ( rolePlayer ) , relationMap ) ) . reduce ( Sets :: intersection ) . orElse ( Collections . emptySet ( ) ) ; if ( possibleRelationTypes . size ( ) == 1 ) { Type relationType = possibleRelationTypes . iterator ( ) . next ( ) ; Label label = relationType . label ( ) ; if ( ! inferredLabels . containsKey ( label ) ) { Statement labelVar = var ( ) ; inferredLabels . put ( label , labelVar ) ; Fragment labelFragment = Fragments . label ( new TypeProperty ( label . getValue ( ) ) , labelVar . var ( ) , ImmutableSet . of ( label ) ) ; inferredFragments . add ( labelFragment ) ; } Statement labelVar = inferredLabels . get ( label ) ; IsaProperty isaProperty = new IsaProperty ( labelVar ) ; EquivalentFragmentSet isaEquivalentFragmentSet = EquivalentFragmentSets . isa ( isaProperty , relationVar , labelVar . var ( ) , relationType . isImplicit ( ) ) ; inferredFragments . addAll ( isaEquivalentFragmentSet . fragments ( ) ) ; } } ) ; return inferredFragments ; }
add label fragment and isa fragment if we can infer any
33,202
private static Multimap < Variable , Type > getInstanceVarTypeMap ( Set < Fragment > allFragments , Map < Variable , Type > labelVarTypeMap ) { Multimap < Variable , Type > instanceVarTypeMap = HashMultimap . create ( ) ; int oldSize ; do { oldSize = instanceVarTypeMap . size ( ) ; allFragments . stream ( ) . filter ( fragment -> labelVarTypeMap . containsKey ( fragment . start ( ) ) ) . filter ( fragment -> fragment instanceof InIsaFragment || fragment instanceof InSubFragment ) . forEach ( fragment -> instanceVarTypeMap . put ( fragment . end ( ) , labelVarTypeMap . get ( fragment . start ( ) ) ) ) ; } while ( oldSize != instanceVarTypeMap . size ( ) ) ; return instanceVarTypeMap ; }
find all vars with direct or indirect out isa edges
33,203
private static Map < Variable , Type > getLabelVarTypeMap ( TransactionOLTP tx , Set < Fragment > allFragments ) { Map < Variable , Type > labelVarTypeMap = new HashMap < > ( ) ; allFragments . stream ( ) . filter ( LabelFragment . class :: isInstance ) . forEach ( fragment -> { SchemaConcept schemaConcept = tx . getSchemaConcept ( Iterators . getOnlyElement ( ( ( LabelFragment ) fragment ) . labels ( ) . iterator ( ) ) ) ; if ( schemaConcept != null && ! schemaConcept . isRole ( ) && ! schemaConcept . isRule ( ) ) { labelVarTypeMap . put ( fragment . start ( ) , schemaConcept . asType ( ) ) ; } } ) ; return labelVarTypeMap ; }
find all vars representing types
33,204
V addInstance ( Schema . BaseType instanceBaseType , BiFunction < VertexElement , T , V > producer , boolean isInferred ) { preCheckForInstanceCreation ( ) ; if ( isAbstract ( ) ) throw TransactionException . addingInstancesToAbstractType ( this ) ; VertexElement instanceVertex = vertex ( ) . tx ( ) . addVertexElement ( instanceBaseType ) ; vertex ( ) . tx ( ) . ruleCache ( ) . ackTypeInstance ( this ) ; if ( ! Schema . MetaSchema . isMetaLabel ( label ( ) ) ) { vertex ( ) . tx ( ) . cache ( ) . addedInstance ( id ( ) ) ; if ( isInferred ) instanceVertex . property ( Schema . VertexProperty . IS_INFERRED , true ) ; } V instance = producer . apply ( instanceVertex , getThis ( ) ) ; assert instance != null : "producer should never return null" ; return instance ; }
Utility method used to create an instance of this type
33,205
public void delete ( ) { Map < Role , Boolean > plays = cachedDirectPlays . get ( ) ; super . delete ( ) ; plays . keySet ( ) . forEach ( roleType -> ( ( RoleImpl ) roleType ) . deleteCachedDirectPlaysByType ( getThis ( ) ) ) ; }
Deletes the concept as type
33,206
private T has ( AttributeType attributeType , Schema . ImplicitType has , Schema . ImplicitType hasValue , Schema . ImplicitType hasOwner , boolean required ) { Label attributeLabel = attributeType . label ( ) ; Role ownerRole = vertex ( ) . tx ( ) . putRoleTypeImplicit ( hasOwner . getLabel ( attributeLabel ) ) ; Role valueRole = vertex ( ) . tx ( ) . putRoleTypeImplicit ( hasValue . getLabel ( attributeLabel ) ) ; RelationType relationType = vertex ( ) . tx ( ) . putRelationTypeImplicit ( has . getLabel ( attributeLabel ) ) . relates ( ownerRole ) . relates ( valueRole ) ; this . play ( ownerRole , required ) ; ( ( AttributeTypeImpl ) attributeType ) . play ( valueRole , false ) ; updateAttributeRelationHierarchy ( attributeType , has , hasValue , hasOwner , ownerRole , valueRole , relationType ) ; return getThis ( ) ; }
Creates a relation type which allows this type and a Attribute type to be linked .
33,207
private void checkNonOverlapOfImplicitRelations ( Schema . ImplicitType implicitType , AttributeType attributeType ) { if ( attributes ( implicitType ) . anyMatch ( rt -> rt . equals ( attributeType ) ) ) { throw TransactionException . duplicateHas ( this , attributeType ) ; } }
Checks if the provided AttributeType is already used in an other implicit relation .
33,208
public static InvalidKBException validationErrors ( List < String > errors ) { StringBuilder message = new StringBuilder ( ) ; message . append ( ErrorMessage . VALIDATION . getMessage ( errors . size ( ) ) ) ; for ( String s : errors ) { message . append ( s ) ; } return create ( message . toString ( ) ) ; }
Thrown on commit when validation errors are found
33,209
public V get ( ) { if ( ! valueRetrieved ) { cacheValue = databaseReader . get ( ) ; valueRetrieved = true ; } return cacheValue ; }
Retrieves the object in the cache . If nothing is cached the database is read .
33,210
private void initialiseMetaConcepts ( TransactionOLTP tx ) { VertexElement type = tx . addTypeVertex ( Schema . MetaSchema . THING . getId ( ) , Schema . MetaSchema . THING . getLabel ( ) , Schema . BaseType . TYPE ) ; VertexElement entityType = tx . addTypeVertex ( Schema . MetaSchema . ENTITY . getId ( ) , Schema . MetaSchema . ENTITY . getLabel ( ) , Schema . BaseType . ENTITY_TYPE ) ; VertexElement relationType = tx . addTypeVertex ( Schema . MetaSchema . RELATION . getId ( ) , Schema . MetaSchema . RELATION . getLabel ( ) , Schema . BaseType . RELATION_TYPE ) ; VertexElement resourceType = tx . addTypeVertex ( Schema . MetaSchema . ATTRIBUTE . getId ( ) , Schema . MetaSchema . ATTRIBUTE . getLabel ( ) , Schema . BaseType . ATTRIBUTE_TYPE ) ; tx . addTypeVertex ( Schema . MetaSchema . ROLE . getId ( ) , Schema . MetaSchema . ROLE . getLabel ( ) , Schema . BaseType . ROLE ) ; tx . addTypeVertex ( Schema . MetaSchema . RULE . getId ( ) , Schema . MetaSchema . RULE . getLabel ( ) , Schema . BaseType . RULE ) ; relationType . property ( Schema . VertexProperty . IS_ABSTRACT , true ) ; resourceType . property ( Schema . VertexProperty . IS_ABSTRACT , true ) ; entityType . property ( Schema . VertexProperty . IS_ABSTRACT , true ) ; relationType . addEdge ( type , Schema . EdgeLabel . SUB ) ; resourceType . addEdge ( type , Schema . EdgeLabel . SUB ) ; entityType . addEdge ( type , Schema . EdgeLabel . SUB ) ; }
This creates the first meta schema in an empty keyspace which has not been initialised yet
33,211
private void copySchemaConceptLabelsToKeyspaceCache ( TransactionOLTP tx ) { copyToCache ( tx . getMetaConcept ( ) ) ; copyToCache ( tx . getMetaRole ( ) ) ; copyToCache ( tx . getMetaRule ( ) ) ; }
Copy schema concepts labels to current KeyspaceCache
33,212
private void copyToCache ( SchemaConcept schemaConcept ) { schemaConcept . subs ( ) . forEach ( concept -> keyspaceCache . cacheLabel ( concept . label ( ) , concept . labelId ( ) ) ) ; }
Copy schema concept and all its subs labels to keyspace cache
33,213
public void close ( ) { if ( isClosed ) { return ; } TransactionOLTP localTx = localOLTPTransactionContainer . get ( ) ; if ( localTx != null ) { localTx . close ( ErrorMessage . SESSION_CLOSED . getMessage ( keyspace ( ) ) ) ; localOLTPTransactionContainer . set ( null ) ; } if ( this . onClose != null ) { this . onClose . accept ( this ) ; } isClosed = true ; }
Close JanusGraph it will not be possible to create new transactions using current instance of Session . This closes current session and local transaction invoking callback function if one is set .
33,214
private static void updateLocalConfiguration ( final JavaSparkContext sparkContext , final Configuration configuration ) { final String [ ] validPropertyNames = { "spark.job.description" , "spark.jobGroup.id" , "spark.job.interruptOnCancel" , "spark.scheduler.pool" } ; for ( String propertyName : validPropertyNames ) { String propertyValue = configuration . get ( propertyName ) ; if ( propertyValue != null ) { LOGGER . info ( "Setting Thread Local SparkContext Property - " + propertyName + " : " + propertyValue ) ; sparkContext . setLocalProperty ( propertyName , configuration . get ( propertyName ) ) ; } } }
When using a persistent context the running Context s configuration will override a passed in configuration . Spark allows us to override these inherited properties via SparkContext . setLocalProperty
33,215
public void putKeyspace ( KeyspaceImpl keyspace ) { if ( containsKeyspace ( keyspace ) ) return ; try ( TransactionOLTP tx = systemKeyspaceSession . transaction ( ) . write ( ) ) { AttributeType < String > keyspaceName = tx . getSchemaConcept ( KEYSPACE_RESOURCE ) ; if ( keyspaceName == null ) { throw GraknServerException . initializationException ( keyspace ) ; } Attribute < String > attribute = keyspaceName . create ( keyspace . name ( ) ) ; if ( attribute . owner ( ) == null ) { tx . < EntityType > getSchemaConcept ( KEYSPACE_ENTITY ) . create ( ) . has ( attribute ) ; } tx . commit ( ) ; existingKeyspaces . add ( keyspace ) ; } catch ( InvalidKBException e ) { throw new RuntimeException ( "Could not add keyspace [" + keyspace + "] to system graph" , e ) ; } }
Logs a new KeyspaceImpl to the KeyspaceManager .
33,216
private void loadSystemSchema ( TransactionOLTP tx ) { AttributeType < String > keyspaceName = tx . putAttributeType ( "keyspace-name" , AttributeType . DataType . STRING ) ; tx . putEntityType ( "keyspace" ) . key ( keyspaceName ) ; }
Loads the system schema inside the provided Transaction .
33,217
public void clear ( ) { ruleMap . clear ( ) ; ruleConversionMap . clear ( ) ; absentTypes . clear ( ) ; checkedTypes . clear ( ) ; checkedRules . clear ( ) ; fruitlessRules . clear ( ) ; }
cleans cache contents
33,218
private String openTextEditor ( ) throws IOException , InterruptedException { String editor = Optional . ofNullable ( System . getenv ( ) . get ( "EDITOR" ) ) . orElse ( EDITOR_DEFAULT ) ; File tempFile = new File ( StandardSystemProperty . JAVA_IO_TMPDIR . value ( ) + EDITOR_FILE ) ; tempFile . createNewFile ( ) ; ProcessBuilder builder = new ProcessBuilder ( "/bin/bash" , "-c" , editor + " </dev/tty >/dev/tty " + tempFile . getAbsolutePath ( ) ) ; builder . start ( ) . waitFor ( ) ; return String . join ( "\n" , Files . readAllLines ( tempFile . toPath ( ) ) ) ; }
Open the user s preferred editor to write a query
33,219
public static ReasonerQueryImpl create ( Conjunction < Statement > pattern , TransactionOLTP tx ) { ReasonerQueryImpl query = new ReasonerQueryImpl ( pattern , tx ) . inferTypes ( ) ; return query . isAtomic ( ) ? new ReasonerAtomicQuery ( query . getAtoms ( ) , tx ) : query ; }
create a reasoner query from a conjunctive pattern with types inferred
33,220
public static ReasonerQueryImpl create ( Set < Atomic > as , TransactionOLTP tx ) { boolean isAtomic = as . stream ( ) . filter ( Atomic :: isSelectable ) . count ( ) == 1 ; return isAtomic ? new ReasonerAtomicQuery ( as , tx ) . inferTypes ( ) : new ReasonerQueryImpl ( as , tx ) . inferTypes ( ) ; }
create a reasoner query from provided set of atomics
33,221
public static ReasonerQueryImpl create ( ReasonerQueryImpl q , ConceptMap sub ) { return q . withSubstitution ( sub ) . inferTypes ( ) ; }
create a reasoner query by combining an existing query and a substitution
33,222
public static ReasonerAtomicQuery atomic ( ReasonerAtomicQuery q , ConceptMap sub ) { return q . withSubstitution ( sub ) . inferTypes ( ) ; }
create an atomic query by combining an existing atomic query and a substitution
33,223
public boolean requiresMaterialisation ( Atom parentAtom ) { if ( requiresMaterialisation == null ) { requiresMaterialisation = parentAtom . requiresMaterialisation ( ) || getHead ( ) . getAtom ( ) . requiresMaterialisation ( ) || hasDisconnectedHead ( ) ; } return requiresMaterialisation ; }
rule requires materialisation in the context of resolving parent atom if parent atom requires materialisation head atom requires materialisation or if the head contains only fresh variables
33,224
public void propertyUnique ( P key , String value ) { GraphTraversal < Vertex , Vertex > traversal = tx ( ) . getTinkerTraversal ( ) . V ( ) . has ( key . name ( ) , value ) ; if ( traversal . hasNext ( ) ) { Vertex vertex = traversal . next ( ) ; if ( ! vertex . equals ( element ( ) ) || traversal . hasNext ( ) ) { if ( traversal . hasNext ( ) ) vertex = traversal . next ( ) ; throw PropertyNotUniqueException . cannotChangeProperty ( element ( ) , vertex , key , value ) ; } } property ( key , value ) ; }
Sets the value of a property with the added restriction that no other vertex can have that property .
33,225
public void startIfNotRunning ( ) { boolean isStorageRunning = daemonExecutor . isProcessRunning ( STORAGE_PIDFILE ) ; if ( isStorageRunning ) { System . out . println ( DISPLAY_NAME + " is already running" ) ; } else { FileUtils . deleteQuietly ( STORAGE_PIDFILE . toFile ( ) ) ; start ( ) ; } }
Attempt to start Storage if it is not already running
33,226
private Stream < Numeric > runComputeMinMaxMedianOrSum ( GraqlCompute . Statistics . Value query ) { Number number = runComputeStatistics ( query ) ; if ( number == null ) return Stream . empty ( ) ; else return Stream . of ( new Numeric ( number ) ) ; }
The Graql compute min max median or sum query run method
33,227
private Stream < Numeric > runComputeMean ( GraqlCompute . Statistics . Value query ) { Map < String , Double > meanPair = runComputeStatistics ( query ) ; if ( meanPair == null ) return Stream . empty ( ) ; Double mean = meanPair . get ( MeanMapReduce . SUM ) / meanPair . get ( MeanMapReduce . COUNT ) ; return Stream . of ( new Numeric ( mean ) ) ; }
The Graql compute mean query run method
33,228
private Stream < Numeric > runComputeStd ( GraqlCompute . Statistics . Value query ) { Map < String , Double > stdTuple = runComputeStatistics ( query ) ; if ( stdTuple == null ) return Stream . empty ( ) ; double squareSum = stdTuple . get ( StdMapReduce . SQUARE_SUM ) ; double sum = stdTuple . get ( StdMapReduce . SUM ) ; double count = stdTuple . get ( StdMapReduce . COUNT ) ; Double std = Math . sqrt ( squareSum / count - ( sum / count ) * ( sum / count ) ) ; return Stream . of ( new Numeric ( std ) ) ; }
The Graql compute std query run method
33,229
private < S > S runComputeStatistics ( GraqlCompute . Statistics . Value query ) { AttributeType . DataType < ? > targetDataType = validateAndGetTargetDataType ( query ) ; if ( ! targetContainsInstance ( query ) ) return null ; Set < LabelId > extendedScopeTypes = convertLabelsToIds ( extendedScopeTypeLabels ( query ) ) ; Set < LabelId > targetTypes = convertLabelsToIds ( targetTypeLabels ( query ) ) ; VertexProgram program = initStatisticsVertexProgram ( query , targetTypes , targetDataType ) ; StatisticsMapReduce < ? > mapReduce = initStatisticsMapReduce ( query , targetTypes , targetDataType ) ; ComputerResult computerResult = compute ( program , mapReduce , extendedScopeTypes ) ; if ( query . method ( ) . equals ( MEDIAN ) ) { Number result = computerResult . memory ( ) . get ( MedianVertexProgram . MEDIAN ) ; LOG . debug ( "Median = {}" , result ) ; return ( S ) result ; } Map < Serializable , S > resultMap = computerResult . memory ( ) . get ( mapReduce . getClass ( ) . getName ( ) ) ; LOG . debug ( "Result = {}" , resultMap . get ( MapReduce . NullObject . instance ( ) ) ) ; return resultMap . get ( MapReduce . NullObject . instance ( ) ) ; }
The compute statistics base algorithm that is called in every compute statistics query
33,230
private AttributeType . DataType < ? > validateAndGetTargetDataType ( GraqlCompute . Statistics . Value query ) { AttributeType . DataType < ? > dataType = null ; for ( Type type : targetTypes ( query ) ) { if ( ! type . isAttributeType ( ) ) throw GraqlQueryException . mustBeAttributeType ( type . label ( ) ) ; AttributeType < ? > attributeType = type . asAttributeType ( ) ; if ( dataType == null ) { dataType = attributeType . dataType ( ) ; if ( ! dataType . equals ( AttributeType . DataType . LONG ) && ! dataType . equals ( AttributeType . DataType . DOUBLE ) ) { throw GraqlQueryException . attributeMustBeANumber ( dataType , attributeType . label ( ) ) ; } } else { if ( ! dataType . equals ( attributeType . dataType ( ) ) ) { throw GraqlQueryException . attributesWithDifferentDataTypes ( query . of ( ) ) ; } } } return dataType ; }
Helper method to validate that the target types are of one data type and get that data type
33,231
private VertexProgram initStatisticsVertexProgram ( GraqlCompute query , Set < LabelId > targetTypes , AttributeType . DataType < ? > targetDataType ) { if ( query . method ( ) . equals ( MEDIAN ) ) return new MedianVertexProgram ( targetTypes , targetDataType ) ; else return new DegreeStatisticsVertexProgram ( targetTypes ) ; }
Helper method to intialise the vertex program for compute statistics queries
33,232
private StatisticsMapReduce < ? > initStatisticsMapReduce ( GraqlCompute . Statistics . Value query , Set < LabelId > targetTypes , AttributeType . DataType < ? > targetDataType ) { Graql . Token . Compute . Method method = query . method ( ) ; if ( method . equals ( MIN ) ) { return new MinMapReduce ( targetTypes , targetDataType , DegreeVertexProgram . DEGREE ) ; } else if ( method . equals ( MAX ) ) { return new MaxMapReduce ( targetTypes , targetDataType , DegreeVertexProgram . DEGREE ) ; } else if ( method . equals ( MEAN ) ) { return new MeanMapReduce ( targetTypes , targetDataType , DegreeVertexProgram . DEGREE ) ; } else if ( method . equals ( STD ) ) { return new StdMapReduce ( targetTypes , targetDataType , DegreeVertexProgram . DEGREE ) ; } else if ( method . equals ( SUM ) ) { return new SumMapReduce ( targetTypes , targetDataType , DegreeVertexProgram . DEGREE ) ; } return null ; }
Helper method to initialise the MapReduce algorithm for compute statistics queries
33,233
private Stream < Numeric > runComputeCount ( GraqlCompute . Statistics . Count query ) { if ( ! scopeContainsInstance ( query ) ) { LOG . debug ( "Count = 0" ) ; return Stream . of ( new Numeric ( 0 ) ) ; } Set < LabelId > scopeTypeLabelIDs = convertLabelsToIds ( scopeTypeLabels ( query ) ) ; Set < LabelId > scopeTypeAndImpliedPlayersLabelIDs = convertLabelsToIds ( scopeTypeLabelsImplicitPlayers ( query ) ) ; scopeTypeAndImpliedPlayersLabelIDs . addAll ( scopeTypeLabelIDs ) ; Map < Integer , Long > count ; ComputerResult result = compute ( new CountVertexProgram ( ) , new CountMapReduceWithAttribute ( ) , scopeTypeAndImpliedPlayersLabelIDs , false ) ; count = result . memory ( ) . get ( CountMapReduceWithAttribute . class . getName ( ) ) ; long finalCount = count . keySet ( ) . stream ( ) . filter ( id -> scopeTypeLabelIDs . contains ( LabelId . of ( id ) ) ) . mapToLong ( count :: get ) . sum ( ) ; if ( count . containsKey ( GraknMapReduce . RESERVED_TYPE_LABEL_KEY ) ) { finalCount += count . get ( GraknMapReduce . RESERVED_TYPE_LABEL_KEY ) ; } LOG . debug ( "Count = {}" , finalCount ) ; return Stream . of ( new Numeric ( finalCount ) ) ; }
Run Graql compute count query
33,234
private Stream < ConceptList > runComputePath ( GraqlCompute . Path query ) { ConceptId fromID = ConceptId . of ( query . from ( ) ) ; ConceptId toID = ConceptId . of ( query . to ( ) ) ; if ( ! scopeContainsInstances ( query , fromID , toID ) ) throw GraqlQueryException . instanceDoesNotExist ( ) ; if ( fromID . equals ( toID ) ) return Stream . of ( new ConceptList ( ImmutableList . of ( fromID ) ) ) ; Set < LabelId > scopedLabelIds = convertLabelsToIds ( scopeTypeLabels ( query ) ) ; ComputerResult result = compute ( new ShortestPathVertexProgram ( fromID , toID ) , null , scopedLabelIds ) ; Multimap < ConceptId , ConceptId > pathsAsEdgeList = HashMultimap . create ( ) ; Map < String , Set < String > > resultFromMemory = result . memory ( ) . get ( ShortestPathVertexProgram . SHORTEST_PATH ) ; resultFromMemory . forEach ( ( id , idSet ) -> idSet . forEach ( id2 -> { pathsAsEdgeList . put ( Schema . conceptIdFromVertexId ( id ) , Schema . conceptIdFromVertexId ( id2 ) ) ; } ) ) ; List < List < ConceptId > > paths ; if ( ! resultFromMemory . isEmpty ( ) ) { paths = getComputePathResultList ( pathsAsEdgeList , fromID ) ; if ( scopeIncludesAttributes ( query ) ) { paths = getComputePathResultListIncludingImplicitRelations ( paths ) ; } } else { paths = Collections . emptyList ( ) ; } return paths . stream ( ) . map ( ConceptList :: new ) ; }
The Graql compute path query run method
33,235
private Stream < ConceptSetMeasure > runComputeCentrality ( GraqlCompute . Centrality query ) { if ( query . using ( ) . equals ( DEGREE ) ) return runComputeDegree ( query ) ; if ( query . using ( ) . equals ( K_CORE ) ) return runComputeCoreness ( query ) ; throw new IllegalArgumentException ( "Unrecognised Graql Compute Centrality algorithm: " + query . method ( ) ) ; }
The Graql compute centrality query run method
33,236
private Stream < ConceptSetMeasure > runComputeDegree ( GraqlCompute . Centrality query ) { Set < Label > targetTypeLabels ; if ( query . of ( ) . isEmpty ( ) ) { targetTypeLabels = scopeTypeLabels ( query ) ; } else { targetTypeLabels = query . of ( ) . stream ( ) . flatMap ( t -> { Label typeLabel = Label . of ( t ) ; Type type = tx . getSchemaConcept ( typeLabel ) ; if ( type == null ) throw GraqlQueryException . labelNotFound ( typeLabel ) ; return type . subs ( ) ; } ) . map ( SchemaConcept :: label ) . collect ( toSet ( ) ) ; } Set < Label > scopeTypeLabels = Sets . union ( scopeTypeLabels ( query ) , targetTypeLabels ) ; if ( ! scopeContainsInstance ( query ) ) { return Stream . empty ( ) ; } Set < LabelId > scopeTypeLabelIDs = convertLabelsToIds ( scopeTypeLabels ) ; Set < LabelId > targetTypeLabelIDs = convertLabelsToIds ( targetTypeLabels ) ; ComputerResult computerResult = compute ( new DegreeVertexProgram ( targetTypeLabelIDs ) , new DegreeDistributionMapReduce ( targetTypeLabelIDs , DegreeVertexProgram . DEGREE ) , scopeTypeLabelIDs ) ; Map < Long , Set < ConceptId > > centralityMap = computerResult . memory ( ) . get ( DegreeDistributionMapReduce . class . getName ( ) ) ; return centralityMap . entrySet ( ) . stream ( ) . map ( centrality -> new ConceptSetMeasure ( centrality . getValue ( ) , centrality . getKey ( ) ) ) ; }
The Graql compute centrality using degree query run method
33,237
private Stream < ConceptSetMeasure > runComputeCoreness ( GraqlCompute . Centrality query ) { long k = query . where ( ) . minK ( ) . get ( ) ; if ( k < 2L ) throw GraqlQueryException . kValueSmallerThanTwo ( ) ; Set < Label > targetTypeLabels ; if ( query . of ( ) . isEmpty ( ) ) { targetTypeLabels = scopeTypeLabels ( query ) ; } else { targetTypeLabels = query . of ( ) . stream ( ) . flatMap ( t -> { Label typeLabel = Label . of ( t ) ; Type type = tx . getSchemaConcept ( typeLabel ) ; if ( type == null ) throw GraqlQueryException . labelNotFound ( typeLabel ) ; if ( type . isRelationType ( ) ) throw GraqlQueryException . kCoreOnRelationType ( typeLabel ) ; return type . subs ( ) ; } ) . map ( SchemaConcept :: label ) . collect ( toSet ( ) ) ; } Set < Label > scopeTypeLabels = Sets . union ( scopeTypeLabels ( query ) , targetTypeLabels ) ; if ( ! scopeContainsInstance ( query ) ) { return Stream . empty ( ) ; } ComputerResult result ; Set < LabelId > scopeTypeLabelIDs = convertLabelsToIds ( scopeTypeLabels ) ; Set < LabelId > targetTypeLabelIDs = convertLabelsToIds ( targetTypeLabels ) ; try { result = compute ( new CorenessVertexProgram ( k ) , new DegreeDistributionMapReduce ( targetTypeLabelIDs , CorenessVertexProgram . CORENESS ) , scopeTypeLabelIDs ) ; } catch ( NoResultException e ) { return Stream . empty ( ) ; } Map < Long , Set < ConceptId > > centralityMap = result . memory ( ) . get ( DegreeDistributionMapReduce . class . getName ( ) ) ; return centralityMap . entrySet ( ) . stream ( ) . map ( centrality -> new ConceptSetMeasure ( centrality . getValue ( ) , centrality . getKey ( ) ) ) ; }
The Graql compute centrality using k - core query run method
33,238
private List < List < ConceptId > > getComputePathResultList ( Multimap < ConceptId , ConceptId > resultGraph , ConceptId fromID ) { List < List < ConceptId > > allPaths = new ArrayList < > ( ) ; List < ConceptId > firstPath = new ArrayList < > ( ) ; firstPath . add ( fromID ) ; Deque < List < ConceptId > > queue = new ArrayDeque < > ( ) ; queue . addLast ( firstPath ) ; while ( ! queue . isEmpty ( ) ) { List < ConceptId > currentPath = queue . pollFirst ( ) ; if ( resultGraph . containsKey ( currentPath . get ( currentPath . size ( ) - 1 ) ) ) { Collection < ConceptId > successors = resultGraph . get ( currentPath . get ( currentPath . size ( ) - 1 ) ) ; Iterator < ConceptId > iterator = successors . iterator ( ) ; for ( int i = 0 ; i < successors . size ( ) - 1 ; i ++ ) { List < ConceptId > extendedPath = new ArrayList < > ( currentPath ) ; extendedPath . add ( iterator . next ( ) ) ; queue . addLast ( extendedPath ) ; } currentPath . add ( iterator . next ( ) ) ; queue . addLast ( currentPath ) ; } else { allPaths . add ( currentPath ) ; } } return allPaths ; }
Helper method to get list of all shortest paths
33,239
private List < List < ConceptId > > getComputePathResultListIncludingImplicitRelations ( List < List < ConceptId > > allPaths ) { List < List < ConceptId > > extendedPaths = new ArrayList < > ( ) ; for ( List < ConceptId > currentPath : allPaths ) { boolean hasAttribute = currentPath . stream ( ) . anyMatch ( conceptID -> tx . getConcept ( conceptID ) . isAttribute ( ) ) ; if ( ! hasAttribute ) { extendedPaths . add ( currentPath ) ; } } int numExtensionAllowed = extendedPaths . isEmpty ( ) ? Integer . MAX_VALUE : 0 ; for ( List < ConceptId > currentPath : allPaths ) { List < ConceptId > extendedPath = new ArrayList < > ( ) ; int numExtension = 0 ; for ( int j = 0 ; j < currentPath . size ( ) - 1 ; j ++ ) { extendedPath . add ( currentPath . get ( j ) ) ; ConceptId resourceRelationId = Utility . getResourceEdgeId ( tx , currentPath . get ( j ) , currentPath . get ( j + 1 ) ) ; if ( resourceRelationId != null ) { numExtension ++ ; if ( numExtension > numExtensionAllowed ) break ; extendedPath . add ( resourceRelationId ) ; } } if ( numExtension == numExtensionAllowed ) { extendedPath . add ( currentPath . get ( currentPath . size ( ) - 1 ) ) ; extendedPaths . add ( extendedPath ) ; } else if ( numExtension < numExtensionAllowed ) { extendedPath . add ( currentPath . get ( currentPath . size ( ) - 1 ) ) ; extendedPaths . clear ( ) ; extendedPaths . add ( extendedPath ) ; numExtensionAllowed = numExtension ; } } return extendedPaths ; }
Helper method t get the list of all shortest path but also including the implicit relations that connect entities and attributes
33,240
private Set < Label > scopeTypeLabelsImplicitPlayers ( GraqlCompute query ) { return scopeTypes ( query ) . filter ( Concept :: isRelationType ) . map ( Concept :: asRelationType ) . filter ( RelationType :: isImplicit ) . flatMap ( RelationType :: roles ) . flatMap ( Role :: players ) . map ( SchemaConcept :: label ) . collect ( toSet ( ) ) ; }
Helper method to get the label IDs of role players in a relation
33,241
private static Set < Label > getAttributeImplicitRelationTypeLabes ( Set < Type > types ) { return types . stream ( ) . filter ( Concept :: isAttributeType ) . map ( attributeType -> Schema . ImplicitType . HAS . getLabel ( attributeType . label ( ) ) ) . collect ( toSet ( ) ) ; }
Helper method to get implicit relation types of attributes
33,242
private ImmutableSet < Type > targetTypes ( Computable . Targetable < ? > query ) { if ( query . of ( ) . isEmpty ( ) ) { throw GraqlQueryException . statisticsAttributeTypesNotSpecified ( ) ; } return query . of ( ) . stream ( ) . map ( t -> { Label label = Label . of ( t ) ; Type type = tx . getSchemaConcept ( label ) ; if ( type == null ) throw GraqlQueryException . labelNotFound ( label ) ; if ( ! type . isAttributeType ( ) ) throw GraqlQueryException . mustBeAttributeType ( type . label ( ) ) ; return type ; } ) . flatMap ( Type :: subs ) . collect ( CommonUtil . toImmutableSet ( ) ) ; }
Helper method to get the types to be included in the query target
33,243
private Set < Label > targetTypeLabels ( Computable . Targetable < ? > query ) { return targetTypes ( query ) . stream ( ) . map ( SchemaConcept :: label ) . collect ( CommonUtil . toImmutableSet ( ) ) ; }
Helper method to get the labels of the type in the query target
33,244
private boolean targetContainsInstance ( GraqlCompute . Statistics . Value query ) { for ( Label attributeType : targetTypeLabels ( query ) ) { for ( Label type : scopeTypeLabels ( query ) ) { Boolean patternExist = tx . stream ( Graql . match ( Graql . var ( "x" ) . has ( attributeType . getValue ( ) , Graql . var ( ) ) , Graql . var ( "x" ) . isa ( Graql . type ( type . getValue ( ) ) ) ) , false ) . iterator ( ) . hasNext ( ) ; if ( patternExist ) return true ; } } return false ; }
Helper method to check whether the concept types in the target have any instances
33,245
private Set < Label > extendedScopeTypeLabels ( GraqlCompute . Statistics . Value query ) { Set < Label > extendedTypeLabels = getAttributeImplicitRelationTypeLabes ( targetTypes ( query ) ) ; extendedTypeLabels . addAll ( scopeTypeLabels ( query ) ) ; extendedTypeLabels . addAll ( query . of ( ) . stream ( ) . map ( Label :: of ) . collect ( toSet ( ) ) ) ; return extendedTypeLabels ; }
Helper method to get all the concept types that should scope of compute query which includes the implicit types between attributes and entities if target types were provided . This is used for compute statistics queries .
33,246
private Stream < Type > scopeTypes ( GraqlCompute query ) { if ( query . in ( ) . isEmpty ( ) ) { ImmutableSet . Builder < Type > typeBuilder = ImmutableSet . builder ( ) ; if ( scopeIncludesAttributes ( query ) ) { tx . getMetaConcept ( ) . subs ( ) . forEach ( typeBuilder :: add ) ; } else { tx . getMetaEntityType ( ) . subs ( ) . forEach ( typeBuilder :: add ) ; tx . getMetaRelationType ( ) . subs ( ) . filter ( relationType -> ! relationType . isImplicit ( ) ) . forEach ( typeBuilder :: add ) ; } return typeBuilder . build ( ) . stream ( ) ; } else { Stream < Type > subTypes = query . in ( ) . stream ( ) . map ( t -> { Label label = Label . of ( t ) ; Type type = tx . getType ( label ) ; if ( type == null ) throw GraqlQueryException . labelNotFound ( label ) ; return type ; } ) . flatMap ( Type :: subs ) ; if ( ! scopeIncludesAttributes ( query ) ) { subTypes = subTypes . filter ( relationType -> ! relationType . isImplicit ( ) ) ; } return subTypes ; } }
Helper method to get the types to be included in the query scope
33,247
private ImmutableSet < Label > scopeTypeLabels ( GraqlCompute query ) { return scopeTypes ( query ) . map ( SchemaConcept :: label ) . collect ( CommonUtil . toImmutableSet ( ) ) ; }
Helper method to get the labels of the type in the query scope
33,248
private boolean scopeContainsInstance ( GraqlCompute query ) { if ( scopeTypeLabels ( query ) . isEmpty ( ) ) return false ; List < Pattern > checkSubtypes = scopeTypeLabels ( query ) . stream ( ) . map ( type -> Graql . var ( "x" ) . isa ( Graql . type ( type . getValue ( ) ) ) ) . collect ( Collectors . toList ( ) ) ; return tx . stream ( Graql . match ( Graql . or ( checkSubtypes ) ) , false ) . iterator ( ) . hasNext ( ) ; }
Helper method to check whether the concept types in the scope have any instances
33,249
private boolean scopeContainsInstances ( GraqlCompute query , ConceptId ... ids ) { for ( ConceptId id : ids ) { Thing thing = tx . getConcept ( id ) ; if ( thing == null || ! scopeTypeLabels ( query ) . contains ( thing . type ( ) . label ( ) ) ) return false ; } return true ; }
Helper method to check if concept instances exist in the query scope
33,250
private boolean scopeIncludesImplicitOrAttributeTypes ( GraqlCompute query ) { if ( query . in ( ) . isEmpty ( ) ) return false ; return query . in ( ) . stream ( ) . anyMatch ( t -> { Label label = Label . of ( t ) ; SchemaConcept type = tx . getSchemaConcept ( label ) ; return ( type != null && ( type . isAttributeType ( ) || type . isImplicit ( ) ) ) ; } ) ; }
Helper method to check whether implicit or attribute types are included in the query scope
33,251
private Set < LabelId > convertLabelsToIds ( Set < Label > labelSet ) { return labelSet . stream ( ) . map ( tx :: convertToId ) . filter ( LabelId :: isValid ) . collect ( toSet ( ) ) ; }
Helper method to convert type labels to IDs
33,252
private static int getMessageCountExcludeSelf ( Messenger < String > messenger , String id ) { Set < String > messageSet = newHashSet ( messenger . receiveMessages ( ) ) ; messageSet . remove ( id ) ; return messageSet . size ( ) ; }
count the messages from relations so need to filter its own msg
33,253
public static TemporaryWriteException indexOverlap ( Vertex vertex , Exception e ) { return new TemporaryWriteException ( String . format ( "Index overlap has led to the accidental sharing of a partially complete vertex {%s}" , vertex ) , e ) ; }
Thrown when multiple transactions overlap in using an index . This results in incomplete vertices being shared between transactions .
33,254
public static TransactionException addingInstancesToAbstractType ( Type type ) { return create ( ErrorMessage . IS_ABSTRACT . getMessage ( type . label ( ) ) ) ; }
Throw when trying to add instances to an abstract Type
33,255
public static TransactionException hasNotAllowed ( Thing thing , Attribute attribute ) { return create ( HAS_INVALID . getMessage ( thing . type ( ) . label ( ) , attribute . type ( ) . label ( ) ) ) ; }
Thrown when a Thing is not allowed to have Attribute of that AttributeType
33,256
public static TransactionException cannotBeDeleted ( SchemaConcept schemaConcept ) { return create ( ErrorMessage . CANNOT_DELETE . getMessage ( schemaConcept . label ( ) ) ) ; }
Thrown when a Type has incoming edges and therefore cannot be deleted
33,257
public static TransactionException invalidAttributeValue ( Object object , AttributeType . DataType dataType ) { return create ( ErrorMessage . INVALID_DATATYPE . getMessage ( object , object . getClass ( ) . getSimpleName ( ) , dataType . name ( ) ) ) ; }
Thrown when creating an Attribute whose value Object does not match attribute data type
33,258
public static TransactionException immutableProperty ( Object oldValue , Object newValue , Enum vertexProperty ) { return create ( ErrorMessage . IMMUTABLE_VALUE . getMessage ( oldValue , newValue , vertexProperty . name ( ) ) ) ; }
Thrown when attempting to mutate a property which is immutable
33,259
public static TransactionException transactionOpen ( TransactionOLTP tx ) { return create ( ErrorMessage . TRANSACTION_ALREADY_OPEN . getMessage ( tx . keyspace ( ) ) ) ; }
Thrown when attempting to open a transaction which is already open
33,260
public static TransactionException transactionReadOnly ( TransactionOLTP tx ) { return create ( ErrorMessage . TRANSACTION_READ_ONLY . getMessage ( tx . keyspace ( ) ) ) ; }
Thrown when attempting to mutate a read only transaction
33,261
public static TransactionException closingFailed ( TransactionOLTP tx , Exception e ) { return new TransactionException ( CLOSE_FAILURE . getMessage ( tx . keyspace ( ) ) , e ) ; }
Thrown when the graph can not be closed due to an unknown reason .
33,262
public static TransactionException invalidPropertyUse ( Concept concept , Schema . VertexProperty property ) { return create ( INVALID_PROPERTY_USE . getMessage ( concept , property ) ) ; }
Thrown when trying to add a Schema . VertexProperty to a Concept which does not accept that type of Schema . VertexProperty
33,263
public static TransactionException changingSuperWillDisconnectRole ( Type oldSuper , Type newSuper , Role role ) { return create ( String . format ( "Cannot change the super type {%s} to {%s} because {%s} is connected to role {%s} which {%s} is not connected to." , oldSuper . label ( ) , newSuper . label ( ) , oldSuper . label ( ) , role . label ( ) , newSuper . label ( ) ) ) ; }
Thrown when changing the super of a Type will result in a Role disconnection which is in use .
33,264
static List < Fragment > nodeToPlanFragments ( Node node , Map < NodeId , Node > nodes , boolean visited ) { List < Fragment > subplan = new LinkedList < > ( ) ; if ( ! visited ) { node . getFragmentsWithoutDependency ( ) . stream ( ) . min ( Comparator . comparingDouble ( Fragment :: fragmentCost ) ) . ifPresent ( firstNodeFragment -> { subplan . add ( firstNodeFragment ) ; node . getFragmentsWithoutDependency ( ) . remove ( firstNodeFragment ) ; } ) ; } node . getFragmentsWithoutDependency ( ) . addAll ( node . getFragmentsWithDependencyVisited ( ) ) ; subplan . addAll ( node . getFragmentsWithoutDependency ( ) . stream ( ) . sorted ( Comparator . comparingDouble ( Fragment :: fragmentCost ) ) . collect ( Collectors . toList ( ) ) ) ; node . getFragmentsWithoutDependency ( ) . clear ( ) ; node . getFragmentsWithDependencyVisited ( ) . clear ( ) ; node . getDependants ( ) . forEach ( fragment -> { Node otherNode = nodes . get ( NodeId . of ( NodeId . NodeType . VAR , fragment . start ( ) ) ) ; if ( node . equals ( otherNode ) ) { otherNode = nodes . get ( NodeId . of ( NodeId . NodeType . VAR , fragment . dependencies ( ) . iterator ( ) . next ( ) ) ) ; } otherNode . getDependants ( ) . remove ( fragment . getInverse ( ) ) ; otherNode . getFragmentsWithDependencyVisited ( ) . add ( fragment ) ; } ) ; node . getDependants ( ) . clear ( ) ; return subplan ; }
convert a Node to a sub - plan updating dependants dependency map
33,265
public Stream < String > toStream ( Stream < ? > objects ) { if ( objects == null ) return Stream . empty ( ) ; return objects . map ( this :: toString ) ; }
Convert a stream of objects into a stream of Strings to be printed
33,266
protected Builder build ( Object object ) { if ( object instanceof Concept ) { return concept ( ( Concept ) object ) ; } else if ( object instanceof Boolean ) { return bool ( ( boolean ) object ) ; } else if ( object instanceof Collection ) { return collection ( ( Collection < ? > ) object ) ; } else if ( object instanceof AnswerGroup < ? > ) { return answerGroup ( ( AnswerGroup < ? > ) object ) ; } else if ( object instanceof ConceptList ) { return conceptList ( ( ConceptList ) object ) ; } else if ( object instanceof ConceptMap ) { return conceptMap ( ( ConceptMap ) object ) ; } else if ( object instanceof ConceptSet ) { if ( object instanceof ConceptSetMeasure ) { return conceptSetMeasure ( ( ConceptSetMeasure ) object ) ; } else { return conceptSet ( ( ConceptSet ) object ) ; } } else if ( object instanceof Numeric ) { return value ( ( Numeric ) object ) ; } else if ( object instanceof Map ) { return map ( ( Map < ? , ? > ) object ) ; } else { return object ( object ) ; } }
Convert any object into its print builder
33,267
public static < T , C extends Comparable > FibonacciHeap < T , C > create ( ) { return FibonacciHeap . create ( Ordering . < C > natural ( ) ) ; }
Create a new FibonacciHeap based on the natural ordering on C
33,268
private List < Entry > siblingsAndBelow ( Entry oEntry ) { if ( oEntry == null ) return Collections . emptyList ( ) ; List < Entry > output = new LinkedList < > ( ) ; for ( Entry entry : getCycle ( oEntry ) ) { if ( entry != null ) { output . add ( entry ) ; output . addAll ( siblingsAndBelow ( entry . oFirstChild ) ) ; } } return output ; }
Depth - first iteration
33,269
private Entry mergeLists ( Entry a , Entry b ) { if ( a == null ) return b ; if ( b == null ) return a ; final Entry aOldNext = a . next ; a . next = b . next ; a . next . previous = a ; b . next = aOldNext ; b . next . previous = b ; return comparator . compare ( a . priority , b . priority ) < 0 ? a : b ; }
Merge two doubly - linked circular lists given a pointer into each . Return the smaller of the two arguments .
33,270
private Entry setParent ( Entry entry , Entry parent ) { unlinkFromNeighbors ( entry ) ; entry . oParent = parent ; parent . oFirstChild = mergeLists ( entry , parent . oFirstChild ) ; parent . degree ++ ; entry . isMarked = false ; return parent ; }
Attaches entry as a child of parent . Returns parent .
33,271
private static void assertEnvironment ( Path graknHome , Path graknProperties ) { String javaVersion = System . getProperty ( "java.specification.version" ) ; if ( ! javaVersion . equals ( "1.8" ) ) { throw new RuntimeException ( ErrorMessage . UNSUPPORTED_JAVA_VERSION . getMessage ( javaVersion ) ) ; } if ( ! graknHome . resolve ( "conf" ) . toFile ( ) . exists ( ) ) { throw new RuntimeException ( ErrorMessage . UNABLE_TO_GET_GRAKN_HOME_FOLDER . getMessage ( ) ) ; } if ( ! graknProperties . toFile ( ) . exists ( ) ) { throw new RuntimeException ( ErrorMessage . UNABLE_TO_GET_GRAKN_CONFIG_FOLDER . getMessage ( ) ) ; } }
Basic environment checks . Grakn should only be ran if users are running Java 8 home folder can be detected and the configuration file grakn . properties exists .
33,272
public final T parse ( String value , Path configFilePath ) { if ( value == null ) { throw new RuntimeException ( ErrorMessage . UNAVAILABLE_PROPERTY . getMessage ( name ( ) , configFilePath ) ) ; } return parser ( ) . read ( value ) ; }
Parse the value of a property .
33,273
public static < T > ConfigKey < T > key ( String value , KeyParser < T > parser ) { return new AutoValue_ConfigKey < > ( value , parser ) ; }
Create a key with the given parser
33,274
public Stream < ConceptMap > materialise ( ConceptMap answer ) { return this . withSubstitution ( answer ) . getAtom ( ) . materialise ( ) . map ( ans -> ans . explain ( answer . explanation ( ) ) ) ; }
materialise this query with the accompanying answer - persist to kb
33,275
public void cacheConcept ( Concept concept ) { conceptCache . put ( concept . id ( ) , concept ) ; if ( concept . isSchemaConcept ( ) ) { SchemaConcept schemaConcept = concept . asSchemaConcept ( ) ; schemaConceptCache . put ( schemaConcept . label ( ) , schemaConcept ) ; labelCache . put ( schemaConcept . label ( ) , schemaConcept . labelId ( ) ) ; } }
Caches a concept so it does not have to be rebuilt later .
33,276
public < X extends Concept > X getCachedConcept ( ConceptId id ) { return ( X ) conceptCache . get ( id ) ; }
Returns a previously built concept
33,277
public < X extends SchemaConcept > X getCachedSchemaConcept ( Label label ) { return ( X ) schemaConceptCache . get ( label ) ; }
Returns a previously built type
33,278
public static GraqlTraversal createTraversal ( Pattern pattern , TransactionOLTP tx ) { Collection < Conjunction < Statement > > patterns = pattern . getDisjunctiveNormalForm ( ) . getPatterns ( ) ; Set < ? extends List < Fragment > > fragments = patterns . stream ( ) . map ( conjunction -> new ConjunctionQuery ( conjunction , tx ) ) . map ( ( ConjunctionQuery query ) -> planForConjunction ( query , tx ) ) . collect ( toImmutableSet ( ) ) ; return GraqlTraversal . create ( fragments ) ; }
Create a traversal plan .
33,279
private static List < Fragment > planForConjunction ( ConjunctionQuery query , TransactionOLTP tx ) { final List < Fragment > plan = new ArrayList < > ( ) ; final Set < Fragment > allFragments = query . getEquivalentFragmentSets ( ) . stream ( ) . flatMap ( EquivalentFragmentSet :: stream ) . collect ( Collectors . toSet ( ) ) ; Set < Fragment > inferredFragments = inferRelationTypes ( tx , allFragments ) ; allFragments . addAll ( inferredFragments ) ; ImmutableMap < NodeId , Node > queryGraphNodes = buildNodesWithDependencies ( allFragments ) ; Collection < Set < Fragment > > connectedFragmentSets = getConnectedFragmentSets ( allFragments ) ; for ( Set < Fragment > connectedFragments : connectedFragmentSets ) { Arborescence < Node > subgraphArborescence = computeArborescence ( connectedFragments , queryGraphNodes , tx ) ; if ( subgraphArborescence != null ) { Map < Node , Map < Node , Fragment > > middleNodeFragmentMapping = virtualMiddleNodeToFragmentMapping ( connectedFragments , queryGraphNodes ) ; List < Fragment > subplan = GreedyTreeTraversal . greedyTraversal ( subgraphArborescence , queryGraphNodes , middleNodeFragmentMapping ) ; plan . addAll ( subplan ) ; } else { Set < Node > unhandledNodes = connectedFragments . stream ( ) . flatMap ( fragment -> fragment . getNodes ( ) . stream ( ) ) . map ( node -> queryGraphNodes . get ( node . getNodeId ( ) ) ) . collect ( Collectors . toSet ( ) ) ; if ( unhandledNodes . size ( ) != 1 ) { throw GraknServerException . create ( "Query planner exception - expected one unhandled node, found " + unhandledNodes . size ( ) ) ; } plan . addAll ( nodeToPlanFragments ( Iterators . getOnlyElement ( unhandledNodes . iterator ( ) ) , queryGraphNodes , false ) ) ; } } List < Fragment > remainingFragments = fragmentsForUnvisitedNodes ( queryGraphNodes , queryGraphNodes . values ( ) ) ; if ( remainingFragments . size ( ) > 0 ) { LOG . warn ( "Expected all fragments to be handled, but found these: " + remainingFragments ) ; plan . addAll ( remainingFragments ) ; } LOG . trace ( "Greedy Plan = {}" , plan ) ; return plan ; }
Create a plan using Edmonds algorithm with greedy approach to execute a single conjunction
33,280
private static List < Fragment > fragmentsForUnvisitedNodes ( Map < NodeId , Node > allNodes , Collection < Node > connectedNodes ) { List < Fragment > subplan = new LinkedList < > ( ) ; Set < Node > nodeWithFragment = connectedNodes . stream ( ) . filter ( node -> ! node . getFragmentsWithoutDependency ( ) . isEmpty ( ) || ! node . getFragmentsWithDependencyVisited ( ) . isEmpty ( ) ) . collect ( Collectors . toSet ( ) ) ; while ( ! nodeWithFragment . isEmpty ( ) ) { nodeWithFragment . forEach ( node -> subplan . addAll ( nodeToPlanFragments ( node , allNodes , false ) ) ) ; nodeWithFragment = connectedNodes . stream ( ) . filter ( node -> ! node . getFragmentsWithoutDependency ( ) . isEmpty ( ) || ! node . getFragmentsWithDependencyVisited ( ) . isEmpty ( ) ) . collect ( Collectors . toSet ( ) ) ; } return subplan ; }
add unvisited node fragments to plan
33,281
private static Collection < Set < Fragment > > getConnectedFragmentSets ( Set < Fragment > allFragments ) { final Map < Integer , Set < Variable > > varSetMap = new HashMap < > ( ) ; final Map < Integer , Set < Fragment > > fragmentSetMap = new HashMap < > ( ) ; final int [ ] index = { 0 } ; allFragments . forEach ( fragment -> { Set < Variable > fragmentVarNameSet = Sets . newHashSet ( fragment . vars ( ) ) ; List < Integer > setsWithVarInCommon = new ArrayList < > ( ) ; varSetMap . forEach ( ( setIndex , varNameSet ) -> { if ( ! Collections . disjoint ( varNameSet , fragmentVarNameSet ) ) { setsWithVarInCommon . add ( setIndex ) ; } } ) ; if ( setsWithVarInCommon . isEmpty ( ) ) { index [ 0 ] += 1 ; varSetMap . put ( index [ 0 ] , fragmentVarNameSet ) ; fragmentSetMap . put ( index [ 0 ] , Sets . newHashSet ( fragment ) ) ; } else { Iterator < Integer > iterator = setsWithVarInCommon . iterator ( ) ; Integer firstSet = iterator . next ( ) ; varSetMap . get ( firstSet ) . addAll ( fragmentVarNameSet ) ; fragmentSetMap . get ( firstSet ) . add ( fragment ) ; while ( iterator . hasNext ( ) ) { Integer nextSet = iterator . next ( ) ; varSetMap . get ( firstSet ) . addAll ( varSetMap . remove ( nextSet ) ) ; fragmentSetMap . get ( firstSet ) . addAll ( fragmentSetMap . remove ( nextSet ) ) ; } } } ) ; return fragmentSetMap . values ( ) ; }
return a collection of set in each set all the fragments are connected
33,282
private static void updateFixedCostSubsReachableByIndex ( ImmutableMap < NodeId , Node > allNodes , Map < Node , Double > nodesWithFixedCost , Set < Fragment > fragments ) { Set < Fragment > validSubFragments = fragments . stream ( ) . filter ( fragment -> { if ( fragment instanceof InSubFragment ) { Node superType = allNodes . get ( NodeId . of ( NodeId . NodeType . VAR , fragment . start ( ) ) ) ; if ( nodesWithFixedCost . containsKey ( superType ) && nodesWithFixedCost . get ( superType ) > 0D ) { Node subType = allNodes . get ( NodeId . of ( NodeId . NodeType . VAR , fragment . end ( ) ) ) ; return ! nodesWithFixedCost . containsKey ( subType ) ; } } return false ; } ) . collect ( Collectors . toSet ( ) ) ; if ( ! validSubFragments . isEmpty ( ) ) { validSubFragments . forEach ( fragment -> { nodesWithFixedCost . put ( allNodes . get ( NodeId . of ( NodeId . NodeType . VAR , fragment . end ( ) ) ) , nodesWithFixedCost . get ( allNodes . get ( NodeId . of ( NodeId . NodeType . VAR , fragment . start ( ) ) ) ) ) ; } ) ; updateFixedCostSubsReachableByIndex ( allNodes , nodesWithFixedCost , fragments ) ; } }
if in - sub starts from an indexed supertype update the fragment cost of in - isa starting from the subtypes
33,283
@ SuppressWarnings ( "unchecked" ) public GraphTraversal < Vertex , Map < String , Element > > getGraphTraversal ( TransactionOLTP tx , Set < Variable > vars ) { if ( fragments ( ) . size ( ) == 1 ) { ImmutableList < Fragment > list = Iterables . getOnlyElement ( fragments ( ) ) ; return getConjunctionTraversal ( tx , tx . getTinkerTraversal ( ) . V ( ) , vars , list ) ; } else { Traversal [ ] traversals = fragments ( ) . stream ( ) . map ( list -> getConjunctionTraversal ( tx , __ . V ( ) , vars , list ) ) . toArray ( Traversal [ ] :: new ) ; GraphTraversal traversal = tx . getTinkerTraversal ( ) . V ( ) . limit ( 1 ) . union ( traversals ) ; return selectVars ( traversal , vars ) ; } }
Because union accepts an array we can t use generics
33,284
public double getComplexity ( ) { double totalCost = 0 ; for ( List < Fragment > list : fragments ( ) ) { totalCost += fragmentListCost ( list ) ; } return totalCost ; }
Get the estimated complexity of the traversal .
33,285
public VertexElement addVertexElementWithEdgeIdProperty ( Schema . BaseType baseType , ConceptId conceptId ) { return executeLockingMethod ( ( ) -> factory ( ) . addVertexElementWithEdgeIdProperty ( baseType , conceptId ) ) ; }
This is only used when reifying a Relation
33,286
private < X > X executeLockingMethod ( Supplier < X > method ) { try { return method . get ( ) ; } catch ( JanusGraphException e ) { if ( e . isCausedBy ( TemporaryLockingException . class ) || e . isCausedBy ( PermanentLockingException . class ) ) { throw TemporaryWriteException . temporaryLock ( e ) ; } else { throw GraknServerException . unknown ( e ) ; } } }
Executes a method which has the potential to throw a TemporaryLockingException or a PermanentLockingException . If the exception is thrown it is wrapped in a GraknServerException so that the transaction can be retried .
33,287
public LabelId convertToId ( Label label ) { if ( transactionCache . isLabelCached ( label ) ) { return transactionCache . convertLabelToId ( label ) ; } return LabelId . invalid ( ) ; }
Converts a Type Label into a type Id for this specific graph . Mapping labels to ids will differ between graphs so be sure to use the correct graph when performing the mapping .
33,288
private LabelId getNextId ( ) { TypeImpl < ? , ? > metaConcept = ( TypeImpl < ? , ? > ) getMetaConcept ( ) ; Integer currentValue = metaConcept . vertex ( ) . property ( Schema . VertexProperty . CURRENT_LABEL_ID ) ; if ( currentValue == null ) { currentValue = Schema . MetaSchema . values ( ) . length + 1 ; } else { currentValue = currentValue + 1 ; } metaConcept . property ( Schema . VertexProperty . CURRENT_LABEL_ID , currentValue ) ; return LabelId . of ( currentValue ) ; }
Gets and increments the current available type id .
33,289
public GraphTraversalSource getTinkerTraversal ( ) { operateOnOpenGraph ( ( ) -> null ) ; if ( graphTraversalSource == null ) { graphTraversalSource = janusGraph . traversal ( ) . withStrategies ( ReadOnlyStrategy . instance ( ) ) ; } return graphTraversalSource ; }
Utility function to get a read - only Tinkerpop traversal .
33,290
protected VertexElement addTypeVertex ( LabelId id , Label label , Schema . BaseType baseType ) { VertexElement vertexElement = addVertexElement ( baseType ) ; vertexElement . property ( Schema . VertexProperty . SCHEMA_LABEL , label . getValue ( ) ) ; vertexElement . property ( Schema . VertexProperty . LABEL_ID , id . getValue ( ) ) ; return vertexElement ; }
Adds a new type vertex which occupies a grakn id . This result in the grakn id count on the meta concept to be incremented .
33,291
private < X > X operateOnOpenGraph ( Supplier < X > supplier ) { if ( ! isLocal ( ) || isClosed ( ) ) throw TransactionException . transactionClosed ( this , this . closedReason ) ; return supplier . get ( ) ; }
An operation on the graph which requires it to be open .
33,292
private TransactionException labelTaken ( SchemaConcept schemaConcept ) { if ( Schema . MetaSchema . isMetaLabel ( schemaConcept . label ( ) ) ) { return TransactionException . reservedLabel ( schemaConcept . label ( ) ) ; } return PropertyNotUniqueException . cannotCreateProperty ( schemaConcept , Schema . VertexProperty . SCHEMA_LABEL , schemaConcept . label ( ) ) ; }
Throws an exception when adding a SchemaConcept using a Label which is already taken
33,293
public void commit ( ) throws InvalidKBException { if ( isClosed ( ) ) { return ; } try { checkMutationAllowed ( ) ; removeInferredConcepts ( ) ; validateGraph ( ) ; synchronized ( keyspaceCache ) { commitTransactionInternal ( ) ; transactionCache . flushToKeyspaceCache ( ) ; } } finally { String closeMessage = ErrorMessage . TX_CLOSED_ON_ACTION . getMessage ( "committed" , keyspace ( ) ) ; closeTransaction ( closeMessage ) ; } }
Commits and closes the transaction without returning CommitLog
33,294
public Optional < CommitLog > commitAndGetLogs ( ) throws InvalidKBException { if ( isClosed ( ) ) { return Optional . empty ( ) ; } try { return commitWithLogs ( ) ; } finally { String closeMessage = ErrorMessage . TX_CLOSED_ON_ACTION . getMessage ( "committed" , keyspace ( ) ) ; closeTransaction ( closeMessage ) ; } }
Commits closes transaction and returns CommitLog .
33,295
public void shard ( ConceptId conceptId ) { ConceptImpl type = getConcept ( conceptId ) ; if ( type == null ) { LOG . warn ( "Cannot shard concept [" + conceptId + "] due to it not existing in the graph" ) ; } else { type . createShard ( ) ; } }
Creates a new shard for the concept
33,296
public long getShardCount ( grakn . core . concept . type . Type concept ) { return TypeImpl . from ( concept ) . shardCount ( ) ; }
Returns the current number of shards the provided grakn . core . concept . type . Type has . This is used in creating more efficient query plans .
33,297
public SessionImpl session ( KeyspaceImpl keyspace ) { JanusGraph graph ; KeyspaceCache cache ; KeyspaceCacheContainer cacheContainer ; ReadWriteLock graphLock ; Lock lock = lockManager . getLock ( getLockingKey ( keyspace ) ) ; lock . lock ( ) ; try { if ( keyspaceCacheMap . containsKey ( keyspace ) ) { cacheContainer = keyspaceCacheMap . get ( keyspace ) ; graph = cacheContainer . graph ( ) ; cache = cacheContainer . cache ( ) ; graphLock = cacheContainer . graphLock ( ) ; } else { keyspaceManager . putKeyspace ( keyspace ) ; graph = janusGraphFactory . openGraph ( keyspace . name ( ) ) ; cache = new KeyspaceCache ( ) ; graphLock = new ReentrantReadWriteLock ( ) ; cacheContainer = new KeyspaceCacheContainer ( cache , graph , graphLock ) ; keyspaceCacheMap . put ( keyspace , cacheContainer ) ; } SessionImpl session = new SessionImpl ( keyspace , config , cache , graph , graphLock ) ; session . setOnClose ( this :: onSessionClose ) ; cacheContainer . addSessionReference ( session ) ; return session ; } finally { lock . unlock ( ) ; } }
Retrieves the Session needed to open the Transaction . This will open a new one Session if it hasn t been opened before
33,298
public void deleteKeyspace ( KeyspaceImpl keyspace ) { Lock lock = lockManager . getLock ( getLockingKey ( keyspace ) ) ; lock . lock ( ) ; try { if ( keyspaceCacheMap . containsKey ( keyspace ) ) { KeyspaceCacheContainer container = keyspaceCacheMap . remove ( keyspace ) ; container . graph ( ) . close ( ) ; container . invalidateSessions ( ) ; } } finally { lock . unlock ( ) ; } }
Invoked when user deletes a keyspace . Remove keyspace reference from internal cache closes graph associated to it and invalidates all the open sessions .
33,299
protected void onSessionClose ( SessionImpl session ) { Lock lock = lockManager . getLock ( getLockingKey ( session . keyspace ( ) ) ) ; lock . lock ( ) ; try { if ( keyspaceCacheMap . containsKey ( session . keyspace ( ) ) ) { KeyspaceCacheContainer cacheContainer = keyspaceCacheMap . get ( session . keyspace ( ) ) ; cacheContainer . removeSessionReference ( session ) ; if ( cacheContainer . referenceCount ( ) == 0 ) { JanusGraph graph = cacheContainer . graph ( ) ; graph . close ( ) ; keyspaceCacheMap . remove ( session . keyspace ( ) ) ; } } } finally { lock . unlock ( ) ; } }
Callback function invoked by Session when it gets closed . This access the keyspaceCacheMap to remove the reference of closed session .