
org.s1.mongodb.table.MongoDBTable Maven / Gradle / Ivy
package org.s1.mongodb.table;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.s1.cluster.dds.beans.CollectionId;
import org.s1.cluster.dds.beans.Id;
import org.s1.cluster.dds.beans.StorageId;
import org.s1.mongodb.MongoDBConnectionHelper;
import org.s1.mongodb.MongoDBFormat;
import org.s1.mongodb.MongoDBQueryHelper;
import org.s1.mongodb.cluster.MongoDBDDS;
import org.s1.objects.MapMethod;
import org.s1.objects.Objects;
import org.s1.table.Table;
import org.s1.table.errors.MoreThanOneFoundException;
import org.s1.table.errors.NotFoundException;
import org.s1.user.AccessDeniedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Grigory Pykhov
*/
public abstract class MongoDBTable extends Table {
private static final Logger LOG = LoggerFactory.getLogger(MongoDBTable.class);
public abstract CollectionId getCollectionId();
public void init() {
//indexes
checkIndexes();
}
public abstract List> getIndexes();
protected void checkIndexes() {
//remove old indexes
DBCollection coll = MongoDBConnectionHelper.getCollection(getCollectionId());
List list = coll.getIndexInfo();
List> indexes = new ArrayList>(getIndexes());
indexes.add(Objects.newArrayList("id"));
for(DBObject o: list){
DBObject key = (DBObject)o.get("key");
if(key.keySet().size()==1 && Objects.equals(key.get("_id"),1)){
continue;
}
boolean exists = false;
for (List b : indexes) {
boolean same = false;
if(key.keySet().size()==b.size()){
same = true;
for(String s:b){
if(!Objects.equals(1,key.get(s))){
same = false;
}
}
}
exists=same;
if(exists)
break;
}
if(exists)
continue;
//removing
if(LOG.isDebugEnabled())
LOG.debug("Drop index "+o+" for collection "+getCollectionId().getCollection());
coll.dropIndex((String)o.get("name"));
}
//add new
for(List b:indexes){
boolean exists = false;
for(DBObject o: list){
DBObject key = (DBObject)o.get("key");
if(key.keySet().size()==1 && Objects.equals(1, key.get("id"))){
boolean same = false;
if(key.keySet().size()==b.size()){
same = true;
for(String s:b){
if(!Objects.equals(1,key.get(s))){
same = false;
}
}
}
exists=same;
if(exists)
break;
}
}
if(exists)
break;
//add new index
if(LOG.isDebugEnabled())
LOG.debug("Ensure index "+b+" for collection "+getCollectionId().getCollection());
DBObject i = new BasicDBObject();
for(String f:b){
i.put(f,1);
}
coll.ensureIndex(i);
}
}
protected void prepareSearch(Map search){
}
protected void prepareSort(Map sort){
}
@MapMethod(names = {"search"})
public long count(Map search) throws AccessDeniedException {
checkAccess();
if(search==null)
search = Objects.newSOHashMap();
prepareSearch(search);
return MongoDBConnectionHelper.getCollection(getCollectionId()).count(MongoDBFormat.fromMap(search));
}
public List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy