com.orientechnologies.orient.core.index.OIndex Java Examples

The following examples show how to use com.orientechnologies.orient.core.index.OIndex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConanUpgrade_1_1.java    From nexus-repository-conan with Eclipse Public License 1.0 6 votes vote down vote up
private Stream<ODocument> findAssets(
    final ODatabaseDocumentTx db,
    final List<String> repositoryNames,
    final String SQL)
{
  return repositoryNames
      .stream()
      .flatMap(repositoryName -> {
        OIndex<?> bucketIdx = db.getMetadata().getIndexManager().getIndex(new OIndexNameBuilder()
            .type("bucket")
            .property(P_REPOSITORY_NAME)
            .build());
        OIdentifiable bucket = (OIdentifiable) bucketIdx.get(repositoryName);
        if (bucket == null) {
          log.debug("Unable to find bucket for {}", repositoryName);
          return Stream.empty();
        }
        List<ODocument> assets =
            db.query(new OSQLSynchQuery<ODocument>(SQL), bucket.getIdentity());
        return assets.stream();
      });
}
 
Example #2
Source File: TestModels.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Test
public void testListModels()
{
	IModel<String> classNameModel = Model.of();
	IModel<OClass> classModel = new OClassModel(classNameModel);
	IModel<List<OProperty>> propertiesModel = new ListOPropertiesModel(classModel, null);
	IModel<List<OIndex<?>>> indexesModel = new ListOIndexesModel(classModel, null);
	List<OProperty> properties = propertiesModel.getObject();
	List<OIndex<?>> indexes = indexesModel.getObject();
	assertNotNull(properties);
	assertNotNull(indexes);
	assertTrue(properties.isEmpty());
	assertTrue(indexes.isEmpty());
	classModel.detach();
	propertiesModel.detach();
	indexesModel.detach();
	
	classNameModel.setObject("OUser");
	properties = propertiesModel.getObject();
	indexes = indexesModel.getObject();
	assertNotNull(properties);
	assertNotNull(indexes);
	assertFalse(properties.isEmpty());
	assertFalse(indexes.isEmpty());
}
 
Example #3
Source File: ListOIndexesModel.java    From wicket-orientdb with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<OIndex<?>> getData() {
	OClass oClass = oClassModel.getObject();
	if(oClass==null)
	{
		return null;
	}
	else if(allIndexesModel==null||Boolean.TRUE.equals(allIndexesModel.getObject()))
	{
		return oClass.getIndexes();
	}
	else
	{
		return oClass.getClassIndexes();
	}
}
 
Example #4
Source File: AbstractIndexesWidget.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
protected AbstractIndexesWidget(String id, IModel<T> model,
                            IModel<ODocument> widgetDocumentModel) {
    super(id, model, widgetDocumentModel);

    IModel<DisplayMode> indexesDisplayMode = getModeModel();
    List<IColumn<OIndex<?>, String>> iColumns = new ArrayList<IColumn<OIndex<?>,String>>();
    iColumns.add(new CheckBoxColumn<OIndex<?>, String, String>(OIndexNameConverter.INSTANCE));
    iColumns.add(new OIndexDefinitionColumn(OIndexPrototyper.NAME, indexesDisplayMode));
    iColumns.add(new OIndexMetaColumn(OIndexPrototyper.TYPE, indexesDisplayMode));
    iColumns.add(new OIndexMetaColumn(OIndexPrototyper.DEF_FIELDS, indexesDisplayMode));
    iColumns.add(new OIndexMetaColumn(OIndexPrototyper.DEF_COLLATE, indexesDisplayMode));
    iColumns.add(new OIndexMetaColumn(OIndexPrototyper.DEF_NULLS_IGNORED, indexesDisplayMode));
    iColumns.add(new OIndexMetaColumn(OIndexPrototyper.SIZE, indexesDisplayMode));
    iColumns.add(new OIndexMetaColumn(OIndexPrototyper.KEY_SIZE, indexesDisplayMode));

    OIndexesDataProvider iProvider = getIndexDataProvider();
    iProvider.setSort("name", SortOrder.ASCENDING);
    GenericTablePanel<OIndex<?>> tablePanel = new GenericTablePanel<OIndex<?>>("tablePanel", iColumns, iProvider ,20);
    iTable = tablePanel.getDataTable();
    iTable.addCommand(new EditSchemaCommand<OIndex<?>>(iTable, indexesDisplayMode));
    iTable.addCommand(new SaveSchemaCommand<OIndex<?>>(iTable, indexesDisplayMode));
    iTable.addCommand(new DeleteOIndexCommand(iTable));
    iTable.setCaptionModel(new ResourceModel("class.indexes"));
    add(tablePanel);
    add(DisableIfPrototypeBehavior.INSTANCE, UpdateOnActionPerformedEventBehavior.INSTANCE_ALL_CONTINUE);
}
 
Example #5
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
private static void checkIndexedPropertiesOnUpdate(final ODocument iRecord, final Collection<OIndex<?>> iIndexes) {
  final Set<String> dirtyFields = new HashSet<String>(Arrays.asList(iRecord.getDirtyFields()));
  if (dirtyFields.isEmpty())
    return;

  for (final OIndex<?> index : iIndexes) {
    final OIndexDefinition indexDefinition = index.getDefinition();
    final List<String> indexFields = indexDefinition.getFields();
    for (final String indexField : indexFields) {
      if (dirtyFields.contains(indexField)) {
        final Object key = index.getDefinition().getDocumentValueToIndex(iRecord);
        if (key instanceof Collection) {
          for (final Object keyItem : (Collection<?>) key) {
            if (keyItem != null)
              index.checkEntry(iRecord, keyItem);
          }
        } else {
          if (key != null)
            index.checkEntry(iRecord, key);
        }
        break;
      }
    }
  }
}
 
Example #6
Source File: FulltextIndexFieldExtension.java    From guice-persist-orient with MIT License 6 votes vote down vote up
private boolean isIndexCorrect(final IndexValidationSupport support, final OClass.INDEX_TYPE type,
                               final FulltextIndex annotation) {
    final OIndex classIndex = support.getIndex();
    final ODocument metadata = classIndex.getConfiguration();
    final Iterable<String> field = metadata.field(STOP_WORDS);
    return support
            .isIndexSigns(metadata.field(INDEX_RADIX),
                    metadata.field(IGNORE_CHARS),
                    metadata.field(SEPARATOR_CHARS),
                    metadata.field(MIN_WORD_LENGTH),
                    Sets.newHashSet(field))
            .matchRequiredSigns(type, annotation.indexRadix(),
                    annotation.ignoreChars(),
                    annotation.separatorChars(),
                    annotation.minWordLength(),
                    Sets.newHashSet(annotation.stopWords()));
}
 
Example #7
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
private void addIndexesEntries(ODocument document) {
  document = checkForLoading(document);

  // STORE THE RECORD IF NEW, OTHERWISE ITS RID
  final OIdentifiable rid = document.getIdentity().isPersistent() ? document.placeholder() : document;

  final OClass cls = document.getSchemaClass();
  if (cls != null) {
    final Collection<OIndex<?>> indexes = cls.getIndexes();
    for (final OIndex<?> index : indexes) {
      final Object key = index.getDefinition().getDocumentValueToIndex(document);
      // SAVE A COPY TO AVOID PROBLEM ON RECYCLING OF THE RECORD
      if (key instanceof Collection) {
        for (final Object keyItem : (Collection<?>) key)
          if (keyItem != null)
            index.put(keyItem, rid);
      } else if (key != null)
        index.put(key, rid);
    }

  }
}
 
Example #8
Source File: OLuceneTextOperator.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
protected OLuceneFullTextIndex involvedIndex(OIdentifiable iRecord, ODocument iCurrentResult, OSQLFilterCondition iCondition,
    Object iLeft, Object iRight) {

  ODocument doc = iRecord.getRecord();
  Set<OIndex<?>> classInvolvedIndexes = getDatabase().getMetadata().getIndexManager()
      .getClassInvolvedIndexes(doc.getClassName(), fields(iCondition));

  OLuceneFullTextIndex idx = null;
  for (OIndex<?> classInvolvedIndex : classInvolvedIndexes) {

    if (classInvolvedIndex.getInternal() instanceof OLuceneFullTextIndex) {
      idx = (OLuceneFullTextIndex) classInvolvedIndex.getInternal();
      break;
    }
  }
  return idx;
}
 
Example #9
Source File: OIndexBuilder.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public OIndex build(final ODatabaseDocumentTx db) {
  checkState(!propertyNames.isEmpty(), "At least one property is required");
  checkState(propertyTypes.size() == propertyNames.size(), "A type must be defined for each property");

  List<OCollate> collates = null;
  if (caseInsensitive) {
    collates = Lists.transform(propertyNames, n -> new OCaseInsensitiveCollate());
  }

  ODocument metadata = new ODocument();
  if (ignoreNullValues) {
    metadata.field("ignoreNullValues", true);
  }

  OIndexDefinition indexDefinition = OIndexDefinitionFactory.createIndexDefinition(type, propertyNames, propertyTypes,
      collates, indexType.name(), null);

  return db.getMetadata().getIndexManager().createIndex(name, indexType.name(), indexDefinition,
      type.getPolymorphicClusterIds(), null, metadata.fields() > 0 ? metadata : null);
}
 
Example #10
Source File: AbstractTagRule.java    From light with Apache License 2.0 6 votes vote down vote up
protected List<String> getTagEntityListDb(String host, String tagId) {
    List<String> entityList = null;
    OrientGraph graph = ServiceLocator.getInstance().getGraph();
    try {
        OIndex<?> tagHostIdIdx = graph.getRawGraph().getMetadata().getIndexManager().getIndex("tagHostIdIdx");
        OCompositeKey key = new OCompositeKey(host, tagId);
        OIdentifiable oid = (OIdentifiable) tagHostIdIdx.get(key);
        if (oid != null) {
            ODocument doc = (ODocument)oid.getRecord();
            entityList = new ArrayList<String>();
            ORidBag entities = doc.field("in_HasTag");
            Iterator<OIdentifiable> iterator = entities.iterator();
            while (iterator.hasNext()) {
                OIdentifiable identifiable = iterator.next();
                entityList.add(identifiable.getIdentity().toString());
            }
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    } finally {
        graph.shutdown();
    }
    return entityList;
}
 
Example #11
Source File: P2Upgrade_1_1.java    From nexus-repository-p2 with Eclipse Public License 1.0 6 votes vote down vote up
private void updateP2AssetNames(final List<String> p2RepositoryNames) {
  OCommandSQL updateAssetCommand = new OCommandSQL(REMOVE_UNNECESSARY_SLASH_FROM_ASSET_NAME);
  DatabaseUpgradeSupport.withDatabaseAndClass(componentDatabaseInstance, ASSET_CLASS_NAME, (db, type) -> {
    OIndex<?> bucketIdx = db.getMetadata().getIndexManager().getIndex(I_REPOSITORY_NAME);
    p2RepositoryNames.forEach(repositoryName -> {
      OIdentifiable bucket = (OIdentifiable) bucketIdx.get(repositoryName);
      if (bucket == null) {
        log.warn("Unable to find bucket for {}", repositoryName);
      }
      else {
        int updates = db.command(updateAssetCommand).execute(bucket.getIdentity());
        if (updates > 0) {
          log.info("Updated {} p2 asset(s) names in repository {}: ", updates, repositoryName);
        }
      }
    });
  });
}
 
Example #12
Source File: RebuildOIndexCommand.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
public RebuildOIndexCommand(OrienteerStructureTable<OIndex<?>, ?> table)
{
	super(new ResourceModel("command.rebuild"), table);
	this.oIndexModel = table.getModel();
	setBootstrapType(BootstrapType.WARNING);
	setIcon(FAIconType.refresh);
}
 
Example #13
Source File: OIndexMetaPanel.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected V getValue(OIndex<?> entity, String critery) {
	if(OIndexPrototyper.DEF_COLLATE.equals(critery))
	{
		OIndexDefinition definition = entity.getDefinition();
		if(definition instanceof OCompositeIndexDefinition) return (V)"composite";
		OCollate collate = definition.getCollate();
		return (V)(collate!=null?collate.getName():null);
	}
	else
	{
		return (V) PropertyResolver.getValue(critery, entity);
	}
}
 
Example #14
Source File: ComponentDatabaseUpgrade_1_5.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void deleteNameCaseInsensitiveIndex(final ODatabaseDocumentTx db) {
  log.info("Deleting old case-insensitive name index on component");
  OIndexManager indexManager = db.getMetadata().getIndexManager();
  OIndex nameCaseInsensitiveIndex = indexManager.getIndex(I_NAME_CASE_INSENSITIVE);
  if (nameCaseInsensitiveIndex != null) {
    indexManager.dropIndex(I_NAME_CASE_INSENSITIVE);
  }
}
 
Example #15
Source File: OrientQuartzSchema.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static OIndex<?> maybeCreateIndex(final OClass clazz, final String name, final String... props) {
  OIndex<?> index = clazz.getClassIndex(name);
  if (index == null) {
    index = clazz.createIndex(name, UNIQUE, props);
  }
  return index;
}
 
Example #16
Source File: OIndexPrototyper.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Override
protected OIndex<?> createInstance(OIndex proxy) {
	OSchema schema = OrientDbWebSession.get().getDatabase().getMetadata().getSchema();
	OClass oClass = schema.getClass(proxy.getDefinition().getClassName());
	String name = proxy.getName();
	List<String> fields = proxy.getDefinition().getFields();
	String type = proxy.getType();
	if(name==null) name=oClass.getName()+"."+fields.get(0);
	ODocument metadata = proxy.getMetadata();
	String algorithm = proxy.getAlgorithm();
	values.keySet().retainAll(RW_ATTRS);
	return oClass.createIndex(name, type, null, metadata, algorithm, fields.toArray(new String[0]));
}
 
Example #17
Source File: OLuceneIndexFactory.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public void onDrop(final ODatabaseInternal iDatabase) {
  try {
    OLogManager.instance().debug(this, "Dropping Lucene indexes...");
    for (OIndex idx : iDatabase.getMetadata().getIndexManager().getIndexes()) {
      if (idx.getInternal() instanceof OLuceneIndex) {
        OLogManager.instance().debug(this, "- index '%s'", idx.getName());
        idx.delete();
      }
    }
  } catch (Exception e) {
    OLogManager.instance().warn(this, "Error on dropping Lucene indexes", e);
  }
}
 
Example #18
Source File: OLuceneTextOperator.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public OIndexCursor executeIndexQuery(OCommandContext iContext, OIndex<?> index, List<Object> keyParams, boolean ascSortOrder) {
  OIndexCursor cursor;
  Object indexResult = index.get(new OFullTextCompositeKey(keyParams).setContext(iContext));
  if (indexResult == null || indexResult instanceof OIdentifiable)
    cursor = new OIndexCursorSingleValue((OIdentifiable) indexResult, new OFullTextCompositeKey(keyParams));
  else
    cursor = new OIndexCursorCollectionValue(((Collection<OIdentifiable>) indexResult).iterator(), new OFullTextCompositeKey(
        keyParams));
  iContext.setVariable("$luceneIndex", true);
  return cursor;
}
 
Example #19
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private static void checkIndexedPropertiesOnCreation(final ODocument iRecord, final Collection<OIndex<?>> iIndexes) {
  for (final OIndex<?> index : iIndexes) {
    final Object key = index.getDefinition().getDocumentValueToIndex(iRecord);
    if (key instanceof Collection) {
      for (final Object keyItem : (Collection<?>) key) {
        if (keyItem != null)
          index.checkEntry(iRecord, keyItem);
      }
    } else {
      if (key != null)
        index.checkEntry(iRecord, key);
    }
  }
}
 
Example #20
Source File: LuceneInsertMultithreadTest.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentInsertWithIndex() throws Exception {

  databaseDocumentTx = new ODatabaseDocumentTx(url);
  if (!url.contains("remote:") && databaseDocumentTx.exists()) {
    databaseDocumentTx.open("admin", "admin");
    databaseDocumentTx.drop();
    databaseDocumentTx.create();
  } else {
    databaseDocumentTx.create();
  }

  OSchema schema = databaseDocumentTx.getMetadata().getSchema();
  if (schema.getClass("City") == null) {
    OClass oClass = schema.createClass("City");

    oClass.createProperty("name", OType.STRING);
    oClass.createIndex("City.name", "FULLTEXT", null, null, "LUCENE", new String[] { "name" });
  }

  Thread[] threads = new Thread[THREADS + RTHREADS];
  for (int i = 0; i < THREADS; ++i)
    threads[i] = new Thread(new LuceneInsertThread(CYCLE), "ConcurrentWriteTest" + i);

  for (int i = THREADS; i < THREADS + RTHREADS; ++i)
    threads[i] = new Thread(new LuceneReadThread(CYCLE), "ConcurrentReadTest" + i);

  for (int i = 0; i < THREADS + RTHREADS; ++i)
    threads[i].start();

  for (int i = 0; i < THREADS + RTHREADS; ++i)
    threads[i].join();

  OIndex idx = schema.getClass("City").getClassIndex("City.name");

  Assert.assertEquals(idx.getSize(), THREADS * CYCLE);
  databaseDocumentTx.drop();
}
 
Example #21
Source File: TestPrototypers.java    From wicket-orientdb with Apache License 2.0 5 votes vote down vote up
@Test
public void testOIndexPrototyper() throws Exception
{
	OClass newClass = wicket.getTester().getSchema().createClass("NewClass");
	OProperty property = newClass.createProperty("name", OType.STRING);
	OIndex<?> newIndex = OIndexPrototyper.newPrototype("NewClass", Arrays.asList("name"));
	assertTrue(property.getAllIndexes().size()==0);
	PropertyResolver.setValue("type", newIndex, "notunique", null);
	assertNotNull(newIndex.getDefinition());
	assertTrue(newIndex.getDefinition().getFields().contains("name"));
	assertTrue(newIndex instanceof IPrototype);
	OIndex<?> realizedNewIndex = ((IPrototype<OIndex<?>>)newIndex).realizePrototype();
	assertEquals(1, property.getAllIndexes().size());
	assertEquals(1, newClass.getIndexes().size());
	
	property = newClass.createProperty("description", OType.STRING);
	newIndex = OIndexPrototyper.newPrototype("NewClass", Arrays.asList("description"));
	PropertyResolver.setValue("type", newIndex, "notunique", null);
	assertEquals(0, property.getAllIndexes().size());
	PropertyResolver.setValue("algorithm", newIndex, ODefaultIndexFactory.SBTREE_ALGORITHM, null);
	ODocument metadata = new ODocument();
	metadata.field("test", "test123", OType.STRING);
	PropertyResolver.setValue("metadata", newIndex, metadata, null);
	realizedNewIndex = ((IPrototype<OIndex<?>>)newIndex).realizePrototype();
	assertEquals(1, property.getAllIndexes().size());
	assertEquals(2, newClass.getIndexes().size());
	assertEquals("test123", realizedNewIndex.getMetadata().field("test"));
	
	wicket.getTester().getSchema().dropClass(newClass.getName());
}
 
Example #22
Source File: OrienteerMainTest.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
@Test
public void testViewClassesAndPropertiesPages() throws Exception
{
	ODatabaseDocument db = getDatabase();
	Collection<OClass> classes = db.getMetadata().getSchema().getClasses();
	PageParameters parameters = new PageParameters();
	
	tester.iterativelyTest(classes, oClass -> {
		parameters.clearNamed();
		parameters.set("className", oClass.getName());
		LOG.info("Rendering page for class '"+oClass.getName()+"'");
		tester.startPage(OClassPage.class, parameters);
		tester.assertRenderedPage(OClassPage.class);
		Collection<OProperty> properties = oClass.properties();
		for (OProperty oProperty : properties)
		{
			parameters.set("propertyName", oProperty.getName());
			LOG.info("Rendering page for property '"+oProperty.getFullName()+"'");
			tester.startPage(OPropertyPage.class, parameters);
			tester.assertRenderedPage(OPropertyPage.class);
		}
		Collection<OIndex<?>> indexes = oClass.getIndexes();
		for (OIndex<?> oIndex : indexes)
		{
			parameters.set("indexName", oIndex.getName());
			LOG.info("Rendering page for index '"+oIndex.getName()+"'");
			tester.startPage(OIndexPage.class, parameters);
			tester.assertRenderedPage(OIndexPage.class);
		}
		return null;
	}).log(LOG, "Stats of rendering schema related pages: class, property, indexes");
}
 
Example #23
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private static void deleteIndexKey(final OIndex<?> index, final ODocument iRecord, final Object origValue) {
  if (origValue instanceof Collection) {
    for (final Object valueItem : (Collection<?>) origValue) {
      if (valueItem != null)
        index.remove(valueItem, iRecord);
    }
  } else if (origValue != null) {
    index.remove(origValue, iRecord);
  }
}
 
Example #24
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private static boolean processCompositeIndexDelete(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
  final OCompositeIndexDefinition indexDefinition = (OCompositeIndexDefinition) index.getDefinition();

  final String multiValueField = indexDefinition.getMultiValueField();

  final List<String> indexFields = indexDefinition.getFields();
  for (final String indexField : indexFields) {
    // REMOVE IT
    if (dirtyFields.contains(indexField)) {
      final List<Object> origValues = new ArrayList<Object>(indexFields.size());

      for (final String field : indexFields) {
        if (!field.equals(multiValueField))
          if (dirtyFields.contains(field))
            origValues.add(iRecord.getOriginalValue(field));
          else
            origValues.add(iRecord.<Object> field(field));
      }

      if (multiValueField != null) {
        final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(multiValueField);
        if (multiValueChangeTimeLine != null) {
          final OTrackedMultiValue fieldValue = iRecord.field(multiValueField);
          final Object restoredMultiValue = fieldValue.returnOriginalState(multiValueChangeTimeLine.getMultiValueChangeEvents());
          origValues.add(indexDefinition.getMultiValueDefinitionIndex(), restoredMultiValue);
        } else if (dirtyFields.contains(multiValueField))
          origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.getOriginalValue(multiValueField));
        else
          origValues.add(indexDefinition.getMultiValueDefinitionIndex(), iRecord.field(multiValueField));
      }

      final Object origValue = indexDefinition.createValue(origValues);
      deleteIndexKey(index, iRecord, origValue);

      return true;
    }
  }
  return false;
}
 
Example #25
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private static void processIndexUpdateFieldAssignment(OIndex<?> index, ODocument iRecord, final Object origValue,
    final Object newValue) {
  if ((origValue instanceof Collection) && (newValue instanceof Collection)) {
    final Set<Object> valuesToRemove = new HashSet<Object>((Collection<?>) origValue);
    final Set<Object> valuesToAdd = new HashSet<Object>((Collection<?>) newValue);

    valuesToRemove.removeAll((Collection<?>) newValue);
    valuesToAdd.removeAll((Collection<?>) origValue);

    for (final Object valueToRemove : valuesToRemove) {
      if (valueToRemove != null) {
        index.remove(valueToRemove, iRecord);
      }
    }

    for (final Object valueToAdd : valuesToAdd) {
      if (valueToAdd != null) {
        index.put(valueToAdd, iRecord);
      }
    }
  } else {
    deleteIndexKey(index, iRecord, origValue);

    if (newValue instanceof Collection) {
      for (final Object newValueItem : (Collection<?>) newValue) {
        index.put(newValueItem, iRecord.placeholder());
      }
    } else if (newValue != null) {
      index.put(newValue, iRecord.placeholder());
    }
  }
}
 
Example #26
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private static void processSingleIndexUpdate(final OIndex<?> index, final Set<String> dirtyFields, final ODocument iRecord) {
  final OIndexDefinition indexDefinition = index.getDefinition();
  final List<String> indexFields = indexDefinition.getFields();

  if (indexFields.isEmpty())
    return;

  final String indexField = indexFields.get(0);
  if (!dirtyFields.contains(indexField))
    return;

  final OMultiValueChangeTimeLine<?, ?> multiValueChangeTimeLine = iRecord.getCollectionTimeLine(indexField);
  if (multiValueChangeTimeLine != null) {
    final OIndexDefinitionMultiValue indexDefinitionMultiValue = (OIndexDefinitionMultiValue) indexDefinition;
    final Map<Object, Integer> keysToAdd = new HashMap<Object, Integer>();
    final Map<Object, Integer> keysToRemove = new HashMap<Object, Integer>();

    for (OMultiValueChangeEvent<?, ?> changeEvent : multiValueChangeTimeLine.getMultiValueChangeEvents()) {
      indexDefinitionMultiValue.processChangeEvent(changeEvent, keysToAdd, keysToRemove);
    }

    for (final Object keyToRemove : keysToRemove.keySet())
      index.remove(keyToRemove, iRecord);

    for (final Object keyToAdd : keysToAdd.keySet())
      index.put(keyToAdd, iRecord.placeholder());

  } else {
    final Object origValue = indexDefinition.createValue(iRecord.getOriginalValue(indexField));
    final Object newValue = indexDefinition.getDocumentValueToIndex(iRecord);

    processIndexUpdateFieldAssignment(index, iRecord, origValue, newValue);
  }
}
 
Example #27
Source File: OLuceneClassIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
private void updateIndexEntries(ODocument iDocument) {
  iDocument = checkForLoading(iDocument);

  final OClass cls = iDocument.getSchemaClass();
  if (cls == null)
    return;

  final Collection<OIndex<?>> indexes = (Collection<OIndex<?>>) getDatabase().getMetadata().getIndexManager().getIndexes();

  if (!indexes.isEmpty()) {
    final Set<String> dirtyFields = new HashSet<String>(Arrays.asList(iDocument.getDirtyFields()));
    if (!dirtyFields.isEmpty()) {
      for (final OIndex<?> index : indexes) {
        if (index.getInternal() instanceof OLuceneIndex && index.getConfiguration().field("metadata") != null) {
          if (index.getDefinition() instanceof OCompositeIndexDefinition)
            processCompositeIndexUpdate(index, dirtyFields, iDocument);
          else
            processSingleIndexUpdate(index, dirtyFields, iDocument);

          if (iDocument.isTrackingChanges()) {
            iDocument.setTrackingChanges(false);
            iDocument.setTrackingChanges(true);
          }
        }
      }
    }
  }

}
 
Example #28
Source File: IndexFieldExtension.java    From guice-persist-orient with MIT License 5 votes vote down vote up
@Override
public void afterRegistration(final ODatabaseObject db, final SchemeDescriptor descriptor,
                              final Field field, final Index annotation) {
    final String property = field.getName();
    final String model = descriptor.schemeClass;
    final String name = MoreObjects.firstNonNull(
            Strings.emptyToNull(annotation.name().trim()), model + '.' + property);
    final OClass clazz = db.getMetadata().getSchema().getClass(model);
    final OIndex<?> classIndex = clazz.getClassIndex(name);
    final OClass.INDEX_TYPE type = annotation.value();
    if (!descriptor.initialRegistration && classIndex != null) {
        final IndexValidationSupport support = new IndexValidationSupport(classIndex, logger);

        support.checkFieldsCompatible(property);

        final boolean correct = support
                .isIndexSigns(classIndex.getDefinition().isNullValuesIgnored())
                .matchRequiredSigns(type, annotation.ignoreNullValues());
        if (!correct) {
            support.dropIndex(db);
        } else {
            // index ok
            return;
        }
    }
    final ODocument metadata = new ODocument()
            .field("ignoreNullValues", annotation.ignoreNullValues());
    clazz.createIndex(name, type.name(), null, metadata, new String[]{property});
    logger.info("Index '{}' ({} [{}]) {} created", name, model, property, type);
}
 
Example #29
Source File: LuceneIndexTypeExtension.java    From guice-persist-orient with MIT License 5 votes vote down vote up
@Override
public void afterRegistration(final ODatabaseObject db, final SchemeDescriptor descriptor,
                              final CompositeLuceneIndex annotation) {
    db.getMetadata().getIndexManager().reload();
    final String name = Strings.emptyToNull(annotation.name().trim());
    Preconditions.checkArgument(name != null, "Index name required");
    final String model = descriptor.schemeClass;
    final OClass clazz = db.getMetadata().getSchema().getClass(model);
    final OIndex<?> classIndex = clazz.getClassIndex(name);
    final OClass.INDEX_TYPE type = OClass.INDEX_TYPE.FULLTEXT;
    final String[] fields = annotation.fields();
    if (!descriptor.initialRegistration && classIndex != null) {
        final IndexValidationSupport support = new IndexValidationSupport(classIndex, logger);
        support.checkTypeCompatible(type);
        support.checkFieldsCompatible(fields);

        final boolean correct = support
                .isIndexSigns(classIndex.getConfiguration().field("algorithm"), getAnalyzer(classIndex))
                .matchRequiredSigns(type, OLuceneIndexFactory.LUCENE_ALGORITHM, annotation.analyzer().getName());
        if (!correct) {
            support.dropIndex(db);
        } else {
            // index ok
            return;
        }
    }
    final ODocument metadata = createMetadata(annotation);
    SchemeUtils.command(db, "create index %s on %s (%s) %s engine %s metadata %s", name, model,
            Joiner.on(',').join(fields), type.name(), OLuceneIndexFactory.LUCENE_ALGORITHM, metadata.toJSON());
    logger.info("Lucene fulltext index '{}' ({} [{}]) created", name, model, Joiner.on(',').join(fields));
}
 
Example #30
Source File: OLuceneIndexPlugin.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
@Override
public void onDrop(final ODatabaseInternal iDatabase) {
  OLogManager.instance().info(this, "Dropping Lucene indexes...");
  for (OIndex idx : iDatabase.getMetadata().getIndexManager().getIndexes()) {
    if (idx.getInternal() instanceof OLuceneIndex) {
      OLogManager.instance().info(this, "- index '%s'", idx.getName());
      idx.delete();
    }
  }
}