If relationship auto-indexing is disabled, Update index for this
relationship manually

@param entityMetadata
@param graphDb
@param autoIndexing
@param node
518572
public void updateRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb,
            Relationship relationship, MetamodelImpl metaModel)
    {
        if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())
        {
            Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName());

            // Remove all existing relationship entries from Index
            relationshipIndex.remove(relationship);

            // Recreate fresh index on this relationship
            addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel);
        }
    }
231268
private static String initUpdateEmbeddedNodeQuery(EntityKeyMetadata entityKeyMetadata) {
		StringBuilder queryBuilder = new StringBuilder( "MERGE " );
		appendEntityNode( "owner", entityKeyMetadata, queryBuilder );
		queryBuilder.append( " MERGE (owner)" );
		return queryBuilder.toString();
	}
132881
private synchronized Map<String, Map<String, Collection<Index<Node>>>> initIndexConfiguration() {
        Map<String, Map<String, Collection<Index<Node>>>> indexesByLabelAndProperty = new HashMap<>();
        try (Transaction tx = graphDatabaseService.beginTx() ) {

            final IndexManager indexManager = graphDatabaseService.index();
            for (String indexName : indexManager.nodeIndexNames()) {

                final Index<Node> index = indexManager.forNodes(indexName);
                Map<String, String> indexConfig = indexManager.getConfiguration(index);

                if (Util.toBoolean(indexConfig.get("autoUpdate"))) {
                    String labels = indexConfig.getOrDefault("labels", "");
                    for (String label : labels.split(":")) {
                        Map<String, Collection<Index<Node>>> propertyKeyToIndexMap = indexesByLabelAndProperty.computeIfAbsent(label, s -> new HashMap<>());
                        String[] keysForLabel = indexConfig.getOrDefault("keysForLabel:" + label, "").split(":");
                        for (String property : keysForLabel) {
                            propertyKeyToIndexMap.computeIfAbsent(property, s -> new ArrayList<>()).add(index);
                        }
                    }
                }
            }
            tx.success();
        }
        return indexesByLabelAndProperty;
    }
610755
void onBuildChildNode(Object childObject, EntityMetadata childMetadata, PersistenceDelegator delegator,
            PersistenceCache pc, Node node, Relation relation)
    {
        Node childNode = generate(childObject, delegator, pc, null);
        if (childNode != null)
        {
            assignNodeLinkProperty(node, relation, childNode);
        }
    }
1246523
public void updateIndex(Set<String> addedNodes, Set<String> removedNodes, Set<String> parentAddedNodes,
      Set<String> parentRemovedNodes)
   {
      // pass lists to search manager 
      if (searchManager != null && (addedNodes.size() > 0 || removedNodes.size() > 0))
      {
         try
         {
            searchManager.updateIndex(removedNodes, addedNodes);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               handler.logErrorChanges(removedNodes, addedNodes);
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
      // pass lists to parent search manager 
      if (parentSearchManager != null && (parentAddedNodes.size() > 0 || parentRemovedNodes.size() > 0))
      {
         try
         {
            parentSearchManager.updateIndex(parentRemovedNodes, parentAddedNodes);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               parentHandler.logErrorChanges(parentRemovedNodes, parentAddedNodes);
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
   }
507614
@Override
    protected void onPersist(EntityMetadata metadata, Object entity, Object id, List<RelationHolder> relationHolders)
    {
        boolean proxyRemoved = removeKunderaProxies(metadata, entity, relationHolders);

        Transaction tx = null;

        s = getStatelessSession();
        tx = onBegin();
        try
        {
            if (!isUpdate)
            {
                id = s.insert(entity);

                // Update foreign Keys
                updateForeignKeys(metadata, id, relationHolders);
                onCommit(tx);/* tx.commit(); */
            }
            else
            {
                s.update(entity);

                if (proxyRemoved)
                {
                    updateForeignKeys(metadata, id, relationHolders);
                }

                onCommit(tx);
            }
        }
        // TODO: Bad code, get rid of these exceptions, currently necessary for
        // handling many to one case
        catch (org.hibernate.exception.ConstraintViolationException e)
        {
            s.update(entity);
            log.info(e.getMessage());
            onCommit(tx);
            // tx.commit();
        }
        catch (HibernateException e)
        {
            log.error("Error while persisting object of {}, Caused by {}.", metadata.getEntityClazz(), e);
            throw new PersistenceException(e);
        }
    }
162364
public void addNode(Node node) {

		long nId = node.getId();
		
		if (this.containsNode(nId))
			throw new DuplicatedNodeException(nId);
		int index = nextNodeId++;
		nodeIdMapping.put(nId, index);

		int aliveIndex = index >> 5;
		int aliveSubIndex = index & 31;

		if (aliveIndex >= aliveNodes.size())
			aliveNodes.add(0);

		aliveNodes.set(aliveIndex, aliveNodes.get(aliveIndex) | (byte)(1 << aliveSubIndex));

		adjacency.add(new IntHashSet[] {new IntHashSet(), new IntHashSet()});

		nodes.add(node);
		numberOfNodes++;
	}
1217419
protected NodeDataIndexing createNodeDataIndexing(TempNodeData tempNode) throws RepositoryException, SQLException,
      IOException, IllegalNameException
   {
      String parentCid;
      QPath parentPath;

      if (tempNode.cpid.equals(Constants.ROOT_PARENT_UUID))
      {
         // root node
         parentCid = null;
         parentPath = Constants.ROOT_PATH;
      }
      else
      {
         parentCid = tempNode.cpid;
         parentPath =
            QPath.makeChildPath(traverseQPath(tempNode.cpid), InternalQName.parse(tempNode.cname), tempNode.cindex);
      }

      // primary type if exists in the list of properties
      SortedSet<TempPropertyData> ptTempProp = tempNode.properties.get(Constants.JCR_PRIMARYTYPE.getAsString());
      ValueData ptValueData = ptTempProp.first().getValueData();
      long ptSize = ptTempProp.first().getSize();
      InternalQName ptName = InternalQName.parse(ValueDataUtil.getString(ptValueData));

      // mixins if exist in the list of properties
      List<ValueData> mixinsData = new ArrayList<ValueData>();
      List<InternalQName> mixins = new ArrayList<InternalQName>();
      long mixinsSize = 0;

      Set<TempPropertyData> mixinsTempProps = tempNode.properties.get(Constants.JCR_MIXINTYPES.getAsString());
      if (mixinsTempProps != null)
      {
         for (TempPropertyData mxnb : mixinsTempProps)
         {
            ValueData vdata = mxnb.getValueData();

            mixinsData.add(vdata);
            mixins.add(InternalQName.parse(ValueDataUtil.getString(vdata)));

            mixinsSize += mxnb.getSize();
         }
      }

      // build node data. No need to load ACL. The node will be pushed directly for reindexing. 
      NodeData nodeData =
         new PersistedNodeData(getIdentifier(tempNode.cid), parentPath, getIdentifier(parentCid), tempNode.cversion,
            tempNode.cnordernumb, ptName, mixins.toArray(new InternalQName[mixins.size()]), null);

      Map<String, PropertyData> childProps = new HashMap<String, PropertyData>();
      for (String propName : tempNode.properties.keySet())
      {
         ExtendedTempPropertyData prop = (ExtendedTempPropertyData)tempNode.properties.get(propName).first();

         String identifier = getIdentifier(prop.id);
         QPath qpath = QPath.makeChildPath(parentPath, InternalQName.parse(prop.name));

         List<ValueData> values = new ArrayList<ValueData>();
         long size = 0;

         if (propName.equals(Constants.JCR_PRIMARYTYPE.getAsString()))
         {
            values.add(ptValueData);
            size = ptSize;
         }
         else if (propName.equals(Constants.JCR_MIXINTYPES.getAsString()))
         {
            values = mixinsData;
            size = mixinsSize;
         }
         else
         {
            for (TempPropertyData tempProp : tempNode.properties.get(propName))
            {
               ExtendedTempPropertyData exTempProp = (ExtendedTempPropertyData)tempProp;

               values.add(exTempProp.getValueData());
               size += exTempProp.getSize();
            }
         }

         // build property data
         PropertyData pdata =
            new PersistedPropertyData(identifier, qpath, getIdentifier(tempNode.cid), prop.version, prop.type, prop.multi, values,
               new SimplePersistedSize(size));

         childProps.put(propName, pdata);
      }

      return new NodeDataIndexing(nodeData, childProps);
   }
673407
@Override
    public void index(Class entityClazz, EntityMetadata m, Map<String, Object> values, Object parentId,
            Class parentClazz)
    {
        Set<String> indexNames = values.keySet();
        for (String idx_Name : indexNames)
        {
            Double value = (Double) values.get(idx_Name);
            Pipeline pipeLine = null;
            try
            {
                if (this.pipeLineOrConnection.getClass().isAssignableFrom(Jedis.class))
                {
                    pipeLine = ((Jedis) this.pipeLineOrConnection).pipelined();
                    pipeLine.zadd(idx_Name, value, parentId.toString());
                    // pipeLine.sync();
                }
                else
                {
                    ((Transaction) this.pipeLineOrConnection).zadd(idx_Name, value, parentId.toString());
                }
            }
            finally
            {
                if (pipeLine != null)
                {
                    pipeLine.sync();
                }
            }
        }

    }
503338
public Node searchNode(Object key, EntityMetadata m, GraphDatabaseService graphDb, boolean skipProxy)
    {
        Node node = null;
        String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();

        final MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
        {
            key = serializeIdAttributeValue(m, metaModel, key);
        }

        if (indexer.isNodeAutoIndexingEnabled(graphDb))
        {
            // Get the Node auto index
            ReadableIndex<Node> autoNodeIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();
            IndexHits<Node> nodesFound = autoNodeIndex.get(idColumnName, key);
            node = getMatchingNodeFromIndexHits(nodesFound, skipProxy);
        }
        else
        {
            // Searching within manually created indexes
            Index<Node> nodeIndex = graphDb.index().forNodes(m.getIndexName());
            IndexHits<Node> nodesFound = nodeIndex.get(idColumnName, key);
            node = getMatchingNodeFromIndexHits(nodesFound, skipProxy);
        }

        return node;
    }
419420
protected void addEntityFromIndexHits(EntityMetadata m, List<Object> entities, IndexHits<Node> hits)
    {
        for (Node node : hits)
        {
            if (node != null)
            {
                Object entity = getEntityWithAssociationFromNode(m, node);
                if (entity != null)
                {

                    entities.add(entity);

                }
            }
        }
    }
894994
private void initialize(AtlasGraph graph) throws RepositoryException, IndexException {
        AtlasGraphManagement management = graph.getManagementSystem();

        try {
            if (management.containsPropertyKey(Constants.VERTEX_TYPE_PROPERTY_KEY)) {
                LOG.info("Global indexes already exist for graph");
                management.commit();

                return;
            }

            /* This is called only once, which is the first time Atlas types are made indexable .*/
            LOG.info("Indexes do not exist, Creating indexes for graph.");

            
            management.createVertexIndex(Constants.VERTEX_INDEX, Constants.BACKING_INDEX, Collections.<AtlasPropertyKey>emptyList());              
            management.createEdgeIndex(Constants.EDGE_INDEX, Constants.BACKING_INDEX);

            // create a composite index for guid as its unique
            createIndexes(management, Constants.GUID_PROPERTY_KEY, String.class, true,
                    AtlasCardinality.SINGLE, true, true);

            // Add creation_timestamp property to Vertex Index (mixed index)
            createIndexes(management, Constants.TIMESTAMP_PROPERTY_KEY, Long.class, false, AtlasCardinality.SINGLE, false, false);

            // Add modification_timestamp property to Vertex Index (mixed index)
            createIndexes(management, Constants.MODIFICATION_TIMESTAMP_PROPERTY_KEY, Long.class, false,
                    AtlasCardinality.SINGLE, false, false);


            // create a mixed index for entity state. Set systemProperty flag deliberately to false
            // so that it doesnt create a composite index which has issues with
            // titan 0.5.4 - Refer https://groups.google.com/forum/#!searchin/aureliusgraphs/hemanth/aureliusgraphs/bx7T843mzXU/fjAsclx7GAAJ
            createIndexes(management, Constants.STATE_PROPERTY_KEY, String.class, false, AtlasCardinality.SINGLE, false, false);

            // Create a composite and mixed index for created by property
            createIndexes(management, Constants.CREATED_BY_KEY, String.class, false,
                    AtlasCardinality.SINGLE, true, true);

            // Create a composite and mixed index for modified by property
            createIndexes(management, Constants.MODIFIED_BY_KEY, String.class, false,
                    AtlasCardinality.SINGLE, true, true);

            // create a composite and mixed index for type since it can be combined with other keys
            createIndexes(management, Constants.ENTITY_TYPE_PROPERTY_KEY, String.class, false, AtlasCardinality.SINGLE,
                    true, true);

            // create a composite and mixed index for type since it can be combined with other keys
            createIndexes(management, Constants.SUPER_TYPES_PROPERTY_KEY, String.class, false, AtlasCardinality.SET,
                    true, true);

            // create a composite and mixed index for traitNames since it can be combined with other
            // keys. Traits must be a set and not a list.
            createIndexes(management, Constants.TRAIT_NAMES_PROPERTY_KEY, String.class, false, AtlasCardinality.SET,
                    true, true);

            // Index for full text search
            createFullTextIndex(management);

            //Indexes for graph backed type system store
            createTypeStoreIndexes(management);
      
            
            commit(management);
            LOG.info("Index creation for global keys complete.");
        } catch (Throwable t) {
            rollback(management);
            throw new RepositoryException(t);
        }
    }
798382
private void addRelationIntoMetadata(Class<?> entityClass, Field relationField, EntityMetadata metadata)
    {
        RelationMetadataProcessor relProcessor = null;
        try
        {
            relProcessor = RelationMetadataProcessorFactory
                    .getRelationMetadataProcessor(relationField, kunderaMetadata);

            this.factory.validate(relationField, new RelationAttributeRule());

            relProcessor = RelationMetadataProcessorFactory
                    .getRelationMetadataProcessor(relationField, kunderaMetadata);

            if (relProcessor != null)
            {
                relProcessor.addRelationIntoMetadata(relationField, metadata);
            }

        }
        catch (PersistenceException pe)
        {
            throw new MetamodelLoaderException("Error with relationship in @Entity(" + entityClass + "."
                    + relationField.getName() + "), reason: " + pe);
        }

    }
340144
public void createIndex(String label, String propertyName) {
        Objects.requireNonNull(label, "label cannot be null");
        Objects.requireNonNull(propertyName, "propertyName cannot be null");
        // get current session
        Neo4JSession session = currentSession();
        // transaction should be ready for io operations
        transaction.readWrite();
        // execute statement
        session.executeStatement(new Statement("CREATE INDEX ON :`" + label + "`(" + propertyName + ")"));
    }
979974
@Override
    public RelationIndexStatusReport call() throws InterruptedException {
        Preconditions.checkNotNull(g, "Graph instance must not be null");
        Preconditions.checkNotNull(relationIndexName, "Index name must not be null");
        Preconditions.checkNotNull(status, "Target status must not be null");

        RelationTypeIndex idx;

        Timer t = new Timer(TimestampProviders.MILLI).start();
        boolean timedOut;
        while (true) {
            SchemaStatus actualStatus = null;
            TitanManagement mgmt = null;
            try {
                mgmt = g.openManagement();
                idx = mgmt.getRelationIndex(mgmt.getRelationType(relationTypeName), relationIndexName);
                actualStatus = idx.getIndexStatus();
                LOGGER.info("Index {} (relation type {}) has status {}", relationIndexName, relationTypeName, actualStatus);
                if (status.equals(actualStatus)) {
                    return new RelationIndexStatusReport(true, relationIndexName, relationTypeName, actualStatus, status, t.elapsed());
                }
            } finally {
                if (null != mgmt)
                    mgmt.rollback(); // Let an exception here propagate up the stack
            }

            timedOut = null != timeout && 0 < t.elapsed().compareTo(timeout);

            if (timedOut) {
                LOGGER.info("Timed out ({}) while waiting for index {} (relation type {}) to reach status {}",
                        timeout, relationIndexName, relationTypeName, status);
                return new RelationIndexStatusReport(false, relationIndexName, relationTypeName, actualStatus, status, t.elapsed());
            }

            Thread.sleep(poll.toMillis());
        }
    }
438651
@Procedure(mode = Mode.WRITE)
    @Description("apoc.index.removeRelationshipByName('name',rel) remove relationship from an index for the given name")
    public void removeRelationshipByName(@Name("name") String name, @Name("relationship") Relationship rel) {
        RelationshipIndex index = getRelationshipIndex(name, null);
        index.remove(rel);
    }
69048
@TimerJ
    public TableMetadataBuilder addIndex(IndexMetadata indexMetadata) {
        indexes.put(indexMetadata.getName(), indexMetadata);
        return this;
    }