- Notifications
You must be signed in to change notification settings - Fork0
A better compressed bitset in Java
License
bitlap/RoaringBitmap
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Maven Central for Bitlap RoaringBitmap | 中文说明 | RoaringBitmapX |
---|---|---|
中文说明 |
Bitsets, also called bitmaps, are commonly used as fast data structures.Unfortunately, they can use too much memory. To compensate, we often usecompressed bitmaps.
Roaring bitmaps are compressed bitmaps which tend to outperform conventionalcompressed bitmaps such as WAH, EWAH or Concise. In some instances, roaring bitmaps canbe hundreds of times faster and they often offer significantly better compression.They can even be faster than uncompressed bitmaps.
Roaring bitmaps are found to work well in many important applications:
Use Roaring for bitmap compression whenever possible. Do not use other bitmap compression methods (Wang et al., SIGMOD 2017)
kudos for making something that makes my software run 5x faster (Charles Parker from BigML)
This library is used by
- Apache Spark,
- Apache Hive,
- Apache Tez,
- Apache Kylin,
- Apache CarbonData,
- Netflix Atlas,
- OpenSearchServer,
- zenvisage,
- Jive Miru,
- Tablesaw,
- Apache Hivemall,
- Gaffer,
- Apache Pinot,
- Apache Druid,
- SirixDB
- EvitaDB
- Apache Iceberg
The YouTube SQL Engine,Google Procella, uses Roaring bitmaps for indexing.Apache Lucene uses Roaring bitmaps, though they have their ownindependent implementation. Derivatives of Lucene such as Solr and Elastic also use Roaring bitmaps.Other platforms such asWhoosh,Microsoft Visual Studio Team Services (VSTS) andPilosa also use Roaring bitmaps with their own implementations. You find Roaring bitmaps inInfluxDB,Bleve,Cloud Torrent, and so forth.
There is a serialized format specification for interoperability between implementations.We have interoperableC/C++, Java andGo implementations.
(c) 2013-... the RoaringBitmap authors
This code is licensed under Apache License, Version 2.0 (AL2.0).
Sets are a fundamental abstraction insoftware. They can be implemented in variousways, as hash sets, as trees, and so forth.In databases and search engines, sets are often an integralpart of indexes. For example, we may need to maintain a setof all documents or rows (represented by numerical identifier)that satisfy some property. Besides adding or removingelements from the set, we need fast functionsto compute the intersection, the union, the difference between sets, and so on.
To implement a setof integers, a particularly appealing strategy is thebitmap (also called bitset or bit vector). Using n bits,we can represent any set made of the integers from the range[0,n): the ith bit is set to one if integer i is present in the set.Commodity processors use words of W=32 or W=64 bits. By combining many such words, we cansupport large values of n. Intersections, unions and differences can then be implementedas bitwise AND, OR and ANDNOT operations.More complicated set functions can also be implemented as bitwise operations.
When the bitset approach is applicable, it can be orders ofmagnitude faster than other possible implementation of a set (e.g., as a hash set)while using several times less memory.
However, a bitset, even a compressed one is not always applicable. For example, ifyou have 1000 random-looking integers, then a simple array might be the best representation.We refer to this case as the "sparse" scenario.
An uncompressed BitSet can use a lot of memory. For example, if you take a BitSetand set the bit at position 1,000,000 to true and you have just over 100kB. That is over 100kBto store the position of one bit. This is wasteful even if you do not care about memory:suppose that you need to compute the intersection between this BitSet and another onethat has a bit at position 1,000,001 to true, then you need to go through all these zeroes,whether you like it or not. That can become very wasteful.
This being said, there are definitively cases where attempting to use compressed bitmaps is wasteful.For example, if you have a small universe size. E.g., your bitmaps represent sets of integersfrom [0,n) where n is small (e.g., n=64 or n=128). If you can use an uncompressed BitSet andit does not blow up your memory usage, then compressed bitmaps are probably not usefulto you. In fact, if you do not need compression, then a BitSet offers remarkable speed.
The sparse scenario is another use case where compressed bitmaps should not be used.Keep in mind that random-looking data is usually not compressible. E.g., if you have a small set of32-bit random integers, it is not mathematically possible to use far less than 32 bits per integer,and attempts at compression can be counterproductive.
Most alternatives to Roaring are part of a larger family of compressed bitmaps that are run-length-encodedbitmaps. They identify long runs of 1s or 0s and they represent them with a marker word.If you have a local mix of 1s and 0, you use an uncompressed word.
There are many formats in this family:
- Oracle's BBC (Byte-aligned Bitmap Code) is an obsolete format at this point: though it may provide good compression,it is likely much slower than more recent alternatives due to excessive branching.
- WAH (Word Aligned Hybrid) is a patented variation on BBC that provides better performance.
- Concise is a variation on the patented WAH. In some specific instances, it can compressmuch better than WAH (up to 2x better), but it is generally slower.
- EWAH (Enhanced Word Aligned Hybrid) is both free of patent, and it is faster than all the above. On the downside, itdoes not compress quite as well. It is faster because it allows some form of "skipping"over uncompressed words. So though none of these formats are great at random access, EWAHis better than the alternatives.
There is a big problem with these formats however that can hurt you badly in some cases: there is no random access. If you want to check whether a given value is present in the set, you have to start from the beginning and "uncompress" the whole thing. This means that if you want to intersect a big set with a large set, you still have to uncompress the whole big set in the worst case...
Roaring solves this problem. It works in the following manner. It divides the data into chunks of 216 integers(e.g., [0, 216), [216, 2 x 216), ...). Within a chunk, it can use an uncompressed bitmap, a simple list of integers,or a list of runs. Whatever format it uses, they all allow you to check for the presence of any one value quickly(e.g., with a binary search). The net result is that Roaring can compute many operations much faster than run-length-encodedformats like WAH, EWAH, Concise... Maybe surprisingly, Roaring also generally offers better compression ratios.
http://www.javadoc.io/doc/org.roaringbitmap/RoaringBitmap/
- Daniel Lemire, Owen Kaser, Nathan Kurz, Luca Deri, Chris O'Hara, François Saint-Jacques, Gregory Ssi-Yan-Kai, Roaring Bitmaps: Implementation of an Optimized Software Library, Software: Practice and Experience 48 (4), 2018arXiv:1709.07821
- Samy Chambi, Daniel Lemire, Owen Kaser, Robert Godin,Better bitmap performance with Roaring bitmaps,Software: Practice and Experience 46 (5), 2016.arXiv:1402.6407 This paper used data fromhttp://lemire.me/data/realroaring2014.html
- Daniel Lemire, Gregory Ssi-Yan-Kai, Owen Kaser, Consistently faster and smaller compressed bitmaps with Roaring, Software: Practice and Experience 46 (11), 2016.arXiv:1603.06549
- Samy Chambi, Daniel Lemire, Robert Godin, Kamel Boukhalfa, Charles Allen, Fangjin Yang, Optimizing Druid with Roaring bitmaps, IDEAS 2016, 2016.http://r-libre.teluq.ca/950/
importorg.bitlap.roaringbitmap.RoaringBitmap;publicclassBasic {publicstaticvoidmain(String[]args) {RoaringBitmaprr =RoaringBitmap.bitmapOf(1,2,3,1000);RoaringBitmaprr2 =newRoaringBitmap();rr2.add(4000L,4255L);rr.select(3);// would return the third value or 1000rr.rank(2);// would return the rank of 2, which is index 1rr.contains(1000);// will return truerr.contains(7);// will return falseRoaringBitmaprror =RoaringBitmap.or(rr,rr2);// new bitmaprr.or(rr2);//in-place computationbooleanequals =rror.equals(rr);// trueif(!equals)thrownewRuntimeException("bug");// number of values stored?longcardinality =rr.getLongCardinality();System.out.println(cardinality);// a "forEach" is faster than this loop, but a loop is possible:for(inti :rr) {System.out.println(i); } }}
Please see the examples folder for more examples, which you can run with./gradlew :examples:runAll
, or run a specific one with./gradlew :examples:runExampleBitmap64
, etc.
Java lacks native unsigned integers but integers are still considered to be unsigned within Roaring and ordered according to Integer.compareUnsigned
. This means that Java will order the numbers like so 0, 1, ..., 2147483647, -2147483648, -2147483647,..., -1. To interpret correctly, you can useInteger.toUnsignedLong
andInteger.toUnsignedString
.
If you want to have your bitmaps lie in memory-mapped files, you canuse the org.bitlap.roaringbitmap.buffer package instead. It contains twoimportant classes, ImmutableRoaringBitmap and MutableRoaringBitmap.MutableRoaringBitmaps are derived from ImmutableRoaringBitmap, so thatyou can convert (cast) a MutableRoaringBitmap to an ImmutableRoaringBitmapin constant time.
An ImmutableRoaringBitmap that is not an instance of a MutableRoaringBitmapis backed by a ByteBuffer which comes with some performance overhead, butwith the added flexibility that the data can reside anywhere (including outsideof the Java heap).
At times you may need to work with bitmaps that reside on disk (instancesof ImmutableRoaringBitmap) and bitmaps that reside in Java memory. If youknow that the bitmaps will reside in Java memory, it is best to useMutableRoaringBitmap instances, not only can they be modified, but theywill also be faster. Moreover, because MutableRoaringBitmap instances arealso ImmutableRoaringBitmap instances, you can write much of your codeexpecting ImmutableRoaringBitmap.
If you write your code expecting ImmutableRoaringBitmap instances, withoutattempting to cast the instances, then your objects will be truly immutable.The MutableRoaringBitmap has a convenience method (toImmutableRoaringBitmap)which is a simple cast back to an ImmutableRoaringBitmap instance.From a language design point of view, instances of the ImmutableRoaringBitmap class are immutable only when used as perthe interface of the ImmutableRoaringBitmap class. Given that the class is not final, it is possibleto modify instances, through other interfaces. Thus we do not take the term "immutable" in a purist manner,but rather in a practical one.
One of our motivations for this design where MutableRoaringBitmap instances can be casteddown to ImmutableRoaringBitmap instances is that bitmaps are often large,or used in a context where memory allocations are to be avoided, so we avoid forcing copies.Copies could be expected if one needs to mix and match ImmutableRoaringBitmap and MutableRoaringBitmap instances.
The following code sample illustrates how to create an ImmutableRoaringBitmapfrom a ByteBuffer. In such instances, the constructor only loads the meta-datain RAM while the actual data is accessed from the ByteBuffer on demand.
importorg.bitlap.roaringbitmap.buffer.*;//...MutableRoaringBitmaprr1 =MutableRoaringBitmap.bitmapOf(1,2,3,1000);MutableRoaringBitmaprr2 =MutableRoaringBitmap.bitmapOf(2,3,1010);ByteArrayOutputStreambos =newByteArrayOutputStream();DataOutputStreamdos =newDataOutputStream(bos);// If there were runs of consecutive values, you could// call rr1.runOptimize(); or rr2.runOptimize(); to improve compressionrr1.serialize(dos);rr2.serialize(dos);dos.close();ByteBufferbb =ByteBuffer.wrap(bos.toByteArray());ImmutableRoaringBitmaprrback1 =newImmutableRoaringBitmap(bb);bb.position(bb.position() +rrback1.serializedSizeInBytes());ImmutableRoaringBitmaprrback2 =newImmutableRoaringBitmap(bb);
Alternatively, we can serialize directly to aByteBuffer
with theserialize(ByteBuffer)
method.
Operations on an ImmutableRoaringBitmap such as and, or, xor, flip, willgenerate a RoaringBitmap which lies in RAM. As the name suggest, theImmutableRoaringBitmap itself cannot be modified.
This design was inspired by Druid.
One can find a complete working example in the test file TestMemoryMapping.java.
Note that you should not mix the classes from the org.roaringbitmap package with the classesfrom the org.bitlap.roaringbitmap.buffer package. They are incompatible. They serializeto the same output however. The performance of the code in org.roaringbitmap package isgenerally superior because there is no overhead due to the use of ByteBuffer instances.
Many applications use Kryo for serialization/deserialization. One canuse Roaring bitmaps with Kryo efficiently thanks to a custom serializer (Kryo 5):
publicclassRoaringSerializerextendsSerializer<RoaringBitmap> {@Overridepublicvoidwrite(Kryokryo,Outputoutput,RoaringBitmapbitmap) {try {bitmap.serialize(newKryoDataOutput(output)); }catch (IOExceptione) {e.printStackTrace();thrownewRuntimeException(); } }@OverridepublicRoaringBitmapread(Kryokryo,Inputinput,Class<?extendsRoaringBitmap>type) {RoaringBitmapbitmap =newRoaringBitmap();try {bitmap.deserialize(newKryoDataInput(input)); }catch (IOExceptione) {e.printStackTrace();thrownewRuntimeException(); }returnbitmap; }}
Though Roaring Bitmaps were designed with the 32-bit case in mind, we have extensions to 64-bit integers.We offer two classes for this purpose:Roaring64NavigableMap
andRoaring64Bitmap
.
TheRoaring64NavigableMap
relies on a conventional red-black-tree. The keys are 32-bit integers representingthe most significant 32~bits of elementswhereas the values of the tree are 32-bit Roaring bitmaps. The 32-bit Roaring bitmaps represent the least significantbits of a set of elements.
The newerRoaring64Bitmap
approach relies on the ART data structure to hold the key/value pair. The keyis made of the most significant 48~bits of elements whereas the values are 16-bit Roaring containers. It is inspired byThe Adaptive Radix Tree: ARTful Indexing for Main-Memory Databases by Leis et al. (ICDE '13).
importorg.bitlap.roaringbitmap.longlong.*;// first Roaring64NavigableMapLongBitmapDataProviderr =Roaring64NavigableMap.bitmapOf(1,2,100,1000);r.addLong(1234);System.out.println(r.contains(1));// trueSystem.out.println(r.contains(3));// falseLongIteratori =r.getLongIterator();while(i.hasNext())System.out.println(i.next());// second Roaring64Bitmapbitmap1 =newRoaring64Bitmap();bitmap2 =newRoaring64Bitmap();intk =1 <<16;longi =Long.MAX_VALUE /2;longbase =i;for (;i <base +10000; ++i) {bitmap1.add(i *k);bitmap2.add(i *k); }b1.and(bitmap2);
The serialization of 64-bit Roaring bitmaps is specified: seehttps://github.com/RoaringBitmap/RoaringFormatSpec#extention-for-64-bit-implementations
However, it is implemented only byRoaring64NavigableMap
, by switching:
Roaring64NavigableMap.SERIALIZATION_MODE = Roaring64NavigableMap.SERIALIZATION_MODE_PORTABLE
RangeBitmap
is a succinct data structure supporting range queries.Each value added to the bitmap is associated with an incremental identifier,and queries produce aRoaringBitmap
of the identifiers associated with valuesthat satisfy the query. Every value added to the bitmap is stored separately,so that if a value is added twice, it will be stored twice, and if that valueis less than some threshold, there will be at least two integers in the resultantRoaringBitmap
.
It is more efficient - in terms of both time and space - toprovide a maximum value. If you don't know the maximum value,provide aLong.MAX_VALUE
. Unsigned order is used like elsewhere inthe library.
varappender =RangeBitmap.appender(1_000_000);appender.add(1L);appender.add(1L);appender.add(100_000L);RangeBitmapbitmap =appender.build();RoaringBitmaplessThan5 =bitmap.lt(5);// {0,1}RoaringBitmapgreaterThanOrEqualTo1 =bitmap.gte(1);// {0, 1, 2}RoaringBitmapgreaterThan1 =bitmap.gt(1);// {2}RoaringBitmapequalTo1 =bitmap.eq(1);// {0, 1}RoaringBitmapnotEqualTo1 =bitmap.neq(1);// {2}
RangeBitmap
is can be written to disk and memory mapped:
varappender =RangeBitmap.appender(1_000_000);appender.add(1L);appender.add(1L);appender.add(100_000L);ByteBufferbuffer =mapBuffer(appender.serializedSizeInBytes());appender.serialize(buffer);RangeBitmapbitmap =RangeBitmap.map(buffer);
The serialization format uses little endian byte order.
- Version 0.7.x requires JDK 8 or better
- Version 0.6.x requires JDK 7 or better
- Version 0.5.x requires JDK 6 or better
To build the project you need maven (version 3).
You can download releases from github:https://github.com/RoaringBitmap/RoaringBitmap/releases
If your project depends on roaring, you can specify the dependency in the Maven "pom.xml" file:
<dependencies> <dependency> <groupId>org.roaringbitmap</groupId> <artifactId>RoaringBitmap</artifactId> <version>0.9.9</version> </dependency> </dependencies>
where you should replace the version number by the version you require.
Get java
./gradlew assemble
will compile./gradlew build
will compile and run the unit tests./gradlew test
will run the tests./gradlew :roaringbitmap:test --tests TestIterators.testIndexIterator4
runs just the testTestIterators.testIndexIterator4
;./gradlew -i :roaringbitmap:test --tests TestRoaringBitmap.issue623
runs just the testissue623
in the classTestRoaringBitmap
while printing out to the console../gradlew bsi:test --tests BufferBSITest.testEQ
run just the testBufferBSITest.testEQ
in thebsi
submodule./gradlew checkstyleMain
will check that you abide by the code style and that the code compiles. We enforce a strict style so that there is no debate as to the proper way to format the code.
If you plan to contribute to RoaringBitmap, you can have loadit up in your favorite IDE.
- For IntelliJ, in the IDE create a new project, possibly from existing sources, choose import, gradle.
- For Eclipse: File, Import, Existing Gradle Projects, Select RoaringBitmap on my disk
Contributions are invited. We enforce the Google Java style.Please run./gradlew checkstyleMain
on your code before submittinga patch.
- I am getting an error about a bad cookie. What is this about?
In the serialized files, part of the first 4 bytes are dedicated to a "cookie"which serves to indicate the file format.
If you try to deserialize or map a bitmap from data that has anunrecognized "cookie", the code will abort the process and reportan error.
This problem will occur to all users who serialized Roaring bitmapsusing versions prior to 0.4.x as they upgrade to version 0.4.x or better.These users need to refresh their serialized bitmaps.
- How big can a Roaring bitmap get?
Given N integers in [0,x), then the serialized size in bytes ofa Roaring bitmap should never exceed this bound:
8 + 9 * ((long)x+65535)/65536 + 2 * N
That is, given a fixed overhead for the universe size (x), Roaringbitmaps never use more than 2 bytes per integer. You can callRoaringBitmap.maximumSerializedSize
for a more precise estimate.
- What is the worst case scenario for Roaring bitmaps?
There is no such thing as a data structure that is always ideal. You shouldmake sure that Roaring bitmaps fit your application profile.There are at least two cases where Roaring bitmaps can be easily replacedby superior alternatives compression-wise:
You have few random values spanning in a large interval (i.e., you havea very sparse set). For example, take the set 0, 65536, 131072, 196608, 262144 ...If this is typical of your application, you might consider using a HashSet ora simple sorted array.
You have dense set of random values that never form runs of continuousvalues. For example, consider the set 0,2,4,...,10000. If this is typical of yourapplication, you might be better served with a conventional bitset (e.g., Java's BitSet class).
How do I select an element at random?
Random random = new Random(); bitmap.select(random.nextInt(bitmap.getCardinality()));
To run JMH benchmarks, use the following command:
$ ./gradlew jmhJar
You can also run specific benchmarks...
$ ./jmh/run.sh 'org.bitlap.roaringbitmap.aggregation.and.identical.*'
https://groups.google.com/forum/#!forum/roaring-bitmaps
This work was supported by NSERC grant number 26143.
About
A better compressed bitset in Java
Resources
License
Stars
Watchers
Forks
Packages0
Languages
- Java97.8%
- Kotlin2.1%
- Other0.1%