Java Code Examples for org.rocksdb.RocksIterator#close()

The following examples show how to use org.rocksdb.RocksIterator#close() . 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: RocksDBStore.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
@Override
public void iterate(byte[] from, EntryConsumer consumer)
    throws IOException {
  RocksIterator it = null;
  try {
    it = db.newIterator();
    if (from != null) {
      it.seek(from);
    } else {
      it.seekToFirst();
    }
    while (it.isValid()) {
      if (!consumer.consume(it.key(), it.value())) {
        break;
      }
      it.next();
    }
  } finally {
    if (it != null) {
      it.close();
    }
  }
}
 
Example 2
Source File: RocksDBLogStorage.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Override
public long getFirstLogIndex() {
    this.readLock.lock();
    RocksIterator it = null;
    try {
        if (this.hasLoadFirstLogIndex) {
            return this.firstLogIndex;
        }
        checkState();
        it = this.db.newIterator(this.defaultHandle, this.totalOrderReadOptions);
        it.seekToFirst();
        if (it.isValid()) {
            final long ret = Bits.getLong(it.key(), 0);
            saveFirstLogIndex(ret);
            setFirstLogIndex(ret);
            return ret;
        }
        return 1L;
    } finally {
        if (it != null) {
            it.close();
        }
        this.readLock.unlock();
    }
}
 
Example 3
Source File: RocksDBStore.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEmpty() throws IOException {
  RocksIterator it = null;
  try {
    it = db.newIterator();
    it.seekToFirst();
    return !it.isValid();
  } finally {
    if (it != null) {
      it.close();
    }
  }
}
 
Example 4
Source File: RocksDBStore.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutablePair<byte[], byte[]> peekAround(int offset,
    byte[] from) throws IOException, IllegalArgumentException {
  RocksIterator it = null;
  try {
    it = db.newIterator();
    if (from == null) {
      it.seekToFirst();
    } else {
      it.seek(from);
    }
    if (!it.isValid()) {
      return null;
    }

    switch (offset) {
    case 0:
      break;
    case 1:
      it.next();
      break;
    case -1:
      it.prev();
      break;
    default:
      throw new IllegalArgumentException(
          "Position can only be -1, 0 " + "or 1, but found " + offset);
    }
    return it.isValid() ? new ImmutablePair<>(it.key(), it.value()) : null;
  } finally {
    if (it != null) {
      it.close();
    }
  }
}
 
Example 5
Source File: RocksDBLookupTable.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<String[]> iterator() {
    final RocksIterator rocksIterator = getRocksIterator();
    rocksIterator.seekToFirst();

    return new Iterator<String[]>() {
        int counter;

        @Override
        public boolean hasNext() {
            boolean valid = rocksIterator.isValid();
            if (!valid) {
                rocksIterator.close();
            }
            return valid;
        }

        @Override
        public String[] next() {
            counter++;
            if (counter % 100000 == 0) {
                logger.info("scanned {} rows from rocksDB", counter);
            }
            String[] result = rowEncoder.decode(new KV(rocksIterator.key(), rocksIterator.value()));
            rocksIterator.next();
            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("not support operation");
        }
    };
}
 
Example 6
Source File: RocksDBDAO.java    From hudi with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a prefix delete and return stream of key-value pairs retrieved.
 *
 * @param columnFamilyName Column Family Name
 * @param prefix Prefix Key
 * @param <T> Type of value stored
 */
public <T extends Serializable> void prefixDelete(String columnFamilyName, String prefix) {
  ValidationUtils.checkArgument(!closed);
  LOG.info("Prefix DELETE (query=" + prefix + ") on " + columnFamilyName);
  final RocksIterator it = getRocksDB().newIterator(managedHandlesMap.get(columnFamilyName));
  it.seek(prefix.getBytes());
  // Find first and last keys to be deleted
  String firstEntry = null;
  String lastEntry = null;
  while (it.isValid() && new String(it.key()).startsWith(prefix)) {
    String result = new String(it.key());
    it.next();
    if (firstEntry == null) {
      firstEntry = result;
    }
    lastEntry = result;
  }
  it.close();

  if (null != firstEntry) {
    try {
      // This will not delete the last entry
      getRocksDB().deleteRange(managedHandlesMap.get(columnFamilyName), firstEntry.getBytes(), lastEntry.getBytes());
      // Delete the last entry
      getRocksDB().delete(lastEntry.getBytes());
    } catch (RocksDBException e) {
      LOG.error("Got exception performing range delete");
      throw new HoodieException(e);
    }
  }
}
 
Example 7
Source File: RocksDbIdentifiers.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
@Override
public MappingIterator mappingIterator() {
  RocksIterator rocksIterator = indices.newIterator();
  return new MappingIterator() {
    @Override
    public void close() {
      rocksIterator.close();
    }

    @Override
    public boolean isValid() {
      return rocksIterator.isValid();
    }

    @Override
    public int identifier() {
      byte[] value = rocksIterator.value();
      return ByteBuffer.wrap(value).getInt();
    }

    @Override
    public String string() {
      byte[] key = rocksIterator.key();
      return new String(key, StandardCharsets.UTF_8);
    }

    @Override
    public void next() {
      rocksIterator.next();
    }
  };
}
 
Example 8
Source File: RocksDbStrings.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
@Override
public MappingIterator mappingIterator() {
  RocksIterator rocksIterator = terms.newIterator();
  rocksIterator.seekToFirst();
  return new MappingIterator() {
    @Override
    public boolean isValid() {
      return rocksIterator.isValid();
    }

    @Override
    public int identifier() {
      byte[] key = rocksIterator.key();
      return ByteBuffer.wrap(key).getInt();
    }

    @Override
    public String string() {
      byte[] value = rocksIterator.value();
      return new String(value, StandardCharsets.UTF_8);
    }

    @Override
    public void next() {
      rocksIterator.next();
    }

    @Override
    public void close() {
      rocksIterator.close();
    }
  };
}
 
Example 9
Source File: RocksDBLookupTable.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<String[]> iterator() {
    final RocksIterator rocksIterator = getRocksIterator();
    rocksIterator.seekToFirst();

    return new Iterator<String[]>() {
        int counter;

        @Override
        public boolean hasNext() {
            boolean valid = rocksIterator.isValid();
            if (!valid) {
                rocksIterator.close();
            }
            return valid;
        }

        @Override
        public String[] next() {
            counter++;
            if (counter % 100000 == 0) {
                logger.info("scanned {} rows from rocksDB", counter);
            }
            String[] result = rowEncoder.decode(new KV(rocksIterator.key(), rocksIterator.value()));
            rocksIterator.next();
            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("not support operation");
        }
    };
}
 
Example 10
Source File: RocksDbStorage.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * Clear the array storage
 */
@Override
public void clear() {
    RocksIterator iterator = db.newIterator();
    while (iterator.isValid())
        try {
            db.remove(iterator.key());
        } catch (RocksDBException e) {
            throw new RuntimeException(e);
        }
    iterator.close();
    size = 0;
}
 
Example 11
Source File: RocksDbStorage.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
/**
 * Clear the array storage
 */
@Override
public void clear() {
    RocksIterator iterator = db.newIterator();
    while (iterator.isValid())
        try {
            db.remove(iterator.key());
        } catch (RocksDBException e) {
            throw new RuntimeException(e);
        }
    iterator.close();
    size = 0;
}
 
Example 12
Source File: RocksDBStore.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
private List<Map.Entry<byte[], byte[]>> getRangeKVs(byte[] startKey,
    int count, boolean sequential,
    MetadataKeyFilters.MetadataKeyFilter... filters)
    throws IOException, IllegalArgumentException {
  List<Map.Entry<byte[], byte[]>> result = new ArrayList<>();
  long start = System.currentTimeMillis();
  if (count < 0) {
    throw new IllegalArgumentException(
        "Invalid count given " + count + ", count must be greater than 0");
  }
  RocksIterator it = null;
  try {
    it = db.newIterator();
    if (startKey == null) {
      it.seekToFirst();
    } else {
      if(get(startKey) == null) {
        // Key not found, return empty list
        return result;
      }
      it.seek(startKey);
    }
    while(it.isValid() && result.size() < count) {
      byte[] currentKey = it.key();
      byte[] currentValue = it.value();

      it.prev();
      final byte[] prevKey = it.isValid() ? it.key() : null;

      it.seek(currentKey);
      it.next();
      final byte[] nextKey = it.isValid() ? it.key() : null;

      if (filters == null) {
        result.add(new AbstractMap.SimpleImmutableEntry<>(currentKey,
            currentValue));
      } else {
        if (Arrays.asList(filters).stream()
            .allMatch(entry -> entry.filterKey(prevKey,
                currentKey, nextKey))) {
          result.add(new AbstractMap.SimpleImmutableEntry<>(currentKey,
              currentValue));
        } else {
          if (result.size() > 0 && sequential) {
            // if the caller asks for a sequential range of results,
            // and we met a dis-match, abort iteration from here.
            // if result is empty, we continue to look for the first match.
            break;
          }
        }
      }
    }
  } finally {
    if (it != null) {
      it.close();
    }
    long end = System.currentTimeMillis();
    long timeConsumed = end - start;
    if (LOG.isDebugEnabled()) {
      if (filters != null) {
        for (MetadataKeyFilters.MetadataKeyFilter filter : filters) {
          int scanned = filter.getKeysScannedNum();
          int hinted = filter.getKeysHintedNum();
          if (scanned > 0 || hinted > 0) {
            LOG.debug(
                "getRangeKVs ({}) numOfKeysScanned={}, numOfKeysHinted={}",
                filter.getClass().getSimpleName(), filter.getKeysScannedNum(),
                filter.getKeysHintedNum());
          }
        }
      }
      LOG.debug("Time consumed for getRangeKVs() is {}ms,"
          + " result length is {}.", timeConsumed, result.size());
    }
  }
  return result;
}
 
Example 13
Source File: TestDB.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Test
    public void testDeleteRange() {
        init();
        WriteBatch wb = new WriteBatch();
        ColumnFamilyHandle cfHandle = CFManager.CFH_DEFAULT;

        long st = System.currentTimeMillis();
        for(int i=100000; i<200000; i++) {
            wb.put(cfHandle, ("1324356527-" + i + "-5-5-345-356-234-232").getBytes(), "tasdfasdgasdfestfordb".getBytes());

            if(i % 30 == 0) {
                RDB.writeAsync(wb);
                wb.clear();
            }
        }
        for(int i=100000; i<200000; i++) {
            wb.put(cfHandle, ("1324356525-" + i + "-5-5-345-356-234-232").getBytes(), "tasdfasdgasdfestfordb".getBytes());

            if(i % 30 == 0) {
                RDB.writeAsync(wb);
                wb.clear();
            }
        }
        for(int i=100000; i<200000; i++) {
            wb.put(cfHandle, ("1324356529-" + i + "-5-5-345-356-234-232").getBytes(), "tasdfasdgasdfestfordb".getBytes());

            if(i % 30 == 0) {
                RDB.writeAsync(wb);
                wb.clear();
            }
        }
        RDB.writeAsync(wb);

        long ed = System.currentTimeMillis();
        System.out.println("write cost :" + (ed - st));

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long start = System.currentTimeMillis();
        RocksIterator it = RDB.newIterator(cfHandle);
        byte[] now = "1324356527".getBytes();
        long count = 0;
        for(it.seek(now); it.isValid(); it.next()) {
//            System.out.println(new String(it.key()) + " " + new String(it.value()));
            count++;
            if(count == 100000)
                break;
        }
        it.close();
        long end = System.currentTimeMillis();
        System.out.println("cost : " + (end - start) + " count:" +count);
        RDB.deleteFilesInRange(CFManager.CFH_DEFAULT, "132435653".getBytes(), "1324356529".getBytes());

        count = 0;
        it = RDB.newIterator(cfHandle);
        now = "1324356525".getBytes();
        for(it.seek(now); it.isValid(); it.next()) {
//            System.out.println(new String(it.key()) + " " + new String(it.value()));
            count++;
            if(count == 100000)
                break;
        }
        it.close();
        end = System.currentTimeMillis();
        System.out.println("cost : " + (end - start) + " count:" +count);

        destructor();
    }
 
Example 14
Source File: TestDB.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Test
    public void testDeleteRange() {
        init();
        WriteBatch wb = new WriteBatch();
        ColumnFamilyHandle cfHandle = CFManager.CFH_DEFAULT;

        long st = System.currentTimeMillis();
        for(int i=100000; i<200000; i++) {
            wb.put(cfHandle, ("1324356527-" + i + "-5-5-345-356-234-232").getBytes(), "tasdfasdgasdfestfordb".getBytes());

            if(i % 30 == 0) {
                RDB.writeAsync(wb);
                wb.clear();
            }
        }
        for(int i=100000; i<200000; i++) {
            wb.put(cfHandle, ("1324356525-" + i + "-5-5-345-356-234-232").getBytes(), "tasdfasdgasdfestfordb".getBytes());

            if(i % 30 == 0) {
                RDB.writeAsync(wb);
                wb.clear();
            }
        }
        for(int i=100000; i<200000; i++) {
            wb.put(cfHandle, ("1324356529-" + i + "-5-5-345-356-234-232").getBytes(), "tasdfasdgasdfestfordb".getBytes());

            if(i % 30 == 0) {
                RDB.writeAsync(wb);
                wb.clear();
            }
        }
        RDB.writeAsync(wb);

        long ed = System.currentTimeMillis();
        System.out.println("write cost :" + (ed - st));

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long start = System.currentTimeMillis();
        RocksIterator it = RDB.newIterator(cfHandle);
        byte[] now = "1324356527".getBytes();
        long count = 0;
        for(it.seek(now); it.isValid(); it.next()) {
//            System.out.println(new String(it.key()) + " " + new String(it.value()));
            count++;
            if(count == 100000)
                break;
        }
        it.close();
        long end = System.currentTimeMillis();
        System.out.println("cost : " + (end - start) + " count:" +count);
        RDB.deleteFilesInRange(CFManager.CFH_DEFAULT, "132435653".getBytes(), "1324356529".getBytes());

        count = 0;
        it = RDB.newIterator(cfHandle);
        now = "1324356525".getBytes();
        for(it.seek(now); it.isValid(); it.next()) {
//            System.out.println(new String(it.key()) + " " + new String(it.value()));
            count++;
            if(count == 100000)
                break;
        }
        it.close();
        end = System.currentTimeMillis();
        System.out.println("cost : " + (end - start) + " count:" +count);

        destructor();
    }
 
Example 15
Source File: RocksDBSenseVectors.java    From biomedicus with Apache License 2.0 4 votes vote down vote up
@Override
public Set<String> senses() {
  return new AbstractSet<String>() {
    @Override
    public Iterator<String> iterator() {
      RocksIterator rocksIterator = rocksDB.newIterator();
      rocksIterator.seekToFirst();
      return new Iterator<String>() {
        boolean closed = false;

        @Override
        public boolean hasNext() {
          return closed || rocksIterator.isValid();
        }

        @Override
        public String next() {
          if (!rocksIterator.isValid()) {
            throw new NoSuchElementException();
          }
          String sense = new String(rocksIterator.key(), StandardCharsets.UTF_8);
          rocksIterator.next();
          if (!rocksIterator.isValid()) {
            closed = true;
            rocksIterator.close();
          }
          return sense;
        }

        @Override
        protected void finalize() {
          if (!closed) {
            rocksIterator.close();
          }
        }
      };
    }

    @Override
    public boolean contains(Object o) {
      return o != null && o instanceof String && containsSense((String) o);
    }

    @Override
    public int size() {
      return RocksDBSenseVectors.this.size();
    }
  };
}
 
Example 16
Source File: RocksDBSenseVectors.java    From biomedicus with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<SparseVector> vectors() {
  return new AbstractCollection<SparseVector>() {
    @Override
    public Iterator<SparseVector> iterator() {
      RocksIterator rocksIterator = rocksDB.newIterator();
      rocksIterator.seekToFirst();
      return new Iterator<SparseVector>() {
        boolean closed = false;

        @Override
        public boolean hasNext() {
          return closed || rocksIterator.isValid();
        }

        @Override
        public SparseVector next() {
          if (!rocksIterator.isValid()) {
            throw new NoSuchElementException();
          }
          SparseVector sparseVector = new SparseVector(rocksIterator.value());
          rocksIterator.next();
          if (!rocksIterator.isValid()) {
            closed = true;
            rocksIterator.close();
          }
          return sparseVector;
        }

        @Override
        protected void finalize() {
          if (!closed) {
            rocksIterator.close();
          }
        }
      };
    }

    @Override
    public int size() {
      return RocksDBSenseVectors.this.size();
    }
  };
}