diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java index 7f882b4ad..810a009db 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/BloomFilter.java @@ -19,12 +19,17 @@ package org.apache.tsfile.utils; import org.apache.tsfile.common.conf.TSFileConfig; +import org.apache.tsfile.common.constant.TsFileConstant; +import org.apache.tsfile.file.metadata.IDeviceID; import org.apache.tsfile.read.common.Path; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.BitSet; +import java.util.Collection; import java.util.Objects; import static org.apache.tsfile.utils.RamUsageEstimator.sizeOfLongArray; @@ -131,6 +136,54 @@ public boolean contains(String value) { return ret; } + /** + * Tests measurements of one device against this filter. Bit i in the result corresponds to the + * ith measurement in iteration order. A null measurement has a clear bit. An empty measurement + * tests the device's time-column path. For an empty device, both path forms (with and without the + * leading separator) are checked. + * + * @throws NullPointerException if the device or the measurement collection is null + */ + public BitSet mightContainBatch(IDeviceID device, Collection measurements) { + Objects.requireNonNull(device); + Objects.requireNonNull(measurements); + BitSet matches = new BitSet(measurements.size()); + if (measurements.isEmpty()) { + return matches; + } + String deviceName = device.toString(); + String prefix = deviceName + TsFileConstant.PATH_SEPARATOR; + // The file's existing hashes use the default charset. Stateful encodings and byte-order marks + // can make encoding the prefix and suffix separately differ from encoding the full path. + Murmur128Hash.PrefixHasher hasher = + StandardCharsets.UTF_8.equals(Charset.defaultCharset()) + ? new Murmur128Hash.PrefixHasher( + prefix.getBytes(StandardCharsets.UTF_8), SEEDS, hashFunctionSize) + : null; + int index = 0; + for (String measurement : measurements) { + if (measurement != null) { + boolean matchesFullPath = + hasher == null ? contains(prefix + measurement) : mightContain(hasher, measurement); + if (matchesFullPath || (deviceName.isEmpty() && contains(measurement))) { + matches.set(index); + } + } + index++; + } + return matches; + } + + private boolean mightContain(Murmur128Hash.PrefixHasher hasher, String measurement) { + hasher.setSuffix(measurement.getBytes(StandardCharsets.UTF_8)); + for (int i = 0; i < hashFunctionSize; i++) { + if (!bits.get(bitIndex(hasher.hash(i), size))) { + return false; + } + } + return true; + } + public byte[] serialize() { return bits.toByteArray(); } @@ -161,7 +214,10 @@ public int hashCode() { } private static int hash(String value, int cap, int seed) { - int res = Murmur128Hash.hash(value, seed); + return bitIndex(Murmur128Hash.hash(value, seed), cap); + } + + private static int bitIndex(int res, int cap) { if (res == Integer.MIN_VALUE) { res = 0; } diff --git a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java index 284d5e8be..d8c17f018 100644 --- a/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java +++ b/java/tsfile/src/main/java/org/apache/tsfile/utils/Murmur128Hash.java @@ -18,8 +18,13 @@ */ package org.apache.tsfile.utils; +import java.util.Arrays; + public class Murmur128Hash { + private static final long C1 = 0x87c37b91114253d5L; + private static final long C2 = 0x4cf5ad432745937fL; + private Murmur128Hash() { // util class } @@ -79,31 +84,21 @@ private static long fmix(long k) { return k; } - private static long innerHash(byte[] key, int offset, int length, long seed) { + static long innerHash(byte[] key, int offset, int length, long seed) { + return innerHash(key, offset, length, length, seed, seed); + } + + // totalLength includes any complete prefix blocks already mixed into h1 and h2. + private static long innerHash( + byte[] key, int offset, int length, int totalLength, long h1, long h2) { final int nblocks = length >> 4; // Process as 128-bit blocks. - long h1 = seed; - long h2 = seed; - long c1 = 0x87c37b91114253d5L; - long c2 = 0x4cf5ad432745937fL; // ---------- // body for (int i = 0; i < nblocks; i++) { long k1 = getBlock(key, offset, i * 2); long k2 = getBlock(key, offset, i * 2 + 1); - k1 *= c1; - k1 = rotl64(k1, 31); - k1 *= c2; - h1 ^= k1; - h1 = rotl64(h1, 27); - h1 += h2; - h1 = h1 * 5 + 0x52dce729; - k2 *= c2; - k2 = rotl64(k2, 33); - k2 *= c1; - h2 ^= k2; - h2 = rotl64(h2, 31); - h2 += h1; - h2 = h2 * 5 + 0x38495ab5; + h1 = mixH1(h1, h2, k1); + h2 = mixH2(h1, h2, k2); } // ---------- // tail @@ -132,9 +127,9 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { // fallthrough case 9: k2 ^= key[offset + 8]; - k2 *= c2; + k2 *= C2; k2 = rotl64(k2, 33); - k2 *= c1; + k2 *= C1; h2 ^= k2; // fallthrough case 8: @@ -160,9 +155,9 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { // fallthrough case 1: k1 ^= (key[offset]); - k1 *= c1; + k1 *= C1; k1 = rotl64(k1, 31); - k1 *= c2; + k1 *= C2; h1 ^= k1; break; default: // 0 @@ -171,8 +166,8 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { } // ---------- // finalization - h1 ^= length; - h2 ^= length; + h1 ^= totalLength; + h2 ^= totalLength; h1 += h2; h2 += h1; h1 = fmix(h1); @@ -181,4 +176,81 @@ private static long innerHash(byte[] key, int offset, int length, long seed) { h2 += h1; return h1 + h2; } + + private static long mixH1(long h1, long h2, long k1) { + k1 *= C1; + k1 = rotl64(k1, 31); + k1 *= C2; + h1 ^= k1; + h1 = rotl64(h1, 27); + h1 += h2; + return h1 * 5 + 0x52dce729; + } + + private static long mixH2(long h1, long h2, long k2) { + k2 *= C2; + k2 = rotl64(k2, 33); + k2 *= C1; + h2 ^= k2; + h2 = rotl64(h2, 31); + h2 += h1; + return h2 * 5 + 0x38495ab5; + } + + /** Reuses complete prefix blocks for all measurements in one Bloom filter lookup. */ + static final class PrefixHasher { + private final long[] prefixH1; + private final long[] prefixH2; + private final byte[] prefix; + private final int prefixBlockBytes; + private final int[] seeds; + private final boolean[] initialized; + private byte[] buffer; + private int totalLength; + + PrefixHasher(byte[] prefix, int[] seeds, int seedCount) { + this.prefix = prefix; + this.seeds = seeds; + prefixBlockBytes = prefix.length - (prefix.length % 16); + totalLength = prefix.length; + buffer = Arrays.copyOfRange(prefix, prefixBlockBytes, prefix.length); + prefixH1 = new long[seedCount]; + prefixH2 = new long[seedCount]; + initialized = new boolean[seedCount]; + } + + void setSuffix(byte[] suffix) { + totalLength = Math.addExact(prefix.length, suffix.length); + int remaining = totalLength - prefixBlockBytes; + int prefixTailLength = prefix.length - prefixBlockBytes; + if (buffer.length < remaining) { + int capacity = Math.max(remaining, buffer.length + (buffer.length >>> 1)); + buffer = new byte[capacity]; + System.arraycopy(prefix, prefixBlockBytes, buffer, 0, prefixTailLength); + } + System.arraycopy(suffix, 0, buffer, prefixTailLength, suffix.length); + } + + int hash(int seedIndex) { + if (!initialized[seedIndex]) { + long h1 = seeds[seedIndex]; + long h2 = h1; + for (int block = 0; block < prefixBlockBytes / 16; block++) { + h1 = mixH1(h1, h2, getBlock(prefix, 0, block * 2)); + h2 = mixH2(h1, h2, getBlock(prefix, 0, block * 2 + 1)); + } + prefixH1[seedIndex] = h1; + prefixH2[seedIndex] = h2; + initialized[seedIndex] = true; + } + return (int) + innerHash( + buffer, + 0, + totalLength - prefixBlockBytes, + totalLength, + prefixH1[seedIndex], + prefixH2[seedIndex]); + } + } } diff --git a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java index ec46d67de..430f5eb55 100644 --- a/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java +++ b/java/tsfile/src/test/java/org/apache/tsfile/utils/BloomFilterTest.java @@ -18,9 +18,25 @@ */ package org.apache.tsfile.utils; +import org.apache.tsfile.file.metadata.IDeviceID; +import org.apache.tsfile.read.common.FullPath; +import org.apache.tsfile.read.common.Path; + import org.junit.Test; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; public class BloomFilterTest { @@ -63,4 +79,164 @@ public void testSerialize() { assertTrue(filter1.contains(value2)); assertTrue(filter1.contains(value3)); } + + @Test + public void testBatchMatchesIndividualPaths() { + List measurements = + Arrays.asList("传感器.温度", null, "absent", "", "s".repeat(80), "x", "传感器.温度"); + IDeviceID.Factory devices = IDeviceID.Factory.DEFAULT_FACTORY; + for (IDeviceID device : + Arrays.asList( + devices.create("d"), + devices.create("root.区域." + "a".repeat(70)), + devices.create(new String[] {"table", null, "region.1", "传感器"}))) { + BloomFilter filter = BloomFilter.getEmptyBloomFilter(0.05, 100); + filter.add(new FullPath(device, "")); + filter.add(new FullPath(device, "传感器.温度")); + filter.add(new FullPath(device, "x")); + assertBatchMatchesSingles(filter, device, measurements); + assertBatchMatchesSingles( + filter, device, Collections.unmodifiableSet(new LinkedHashSet<>(measurements))); + assertBatchMatchesSingles( + filter, IDeviceID.Factory.DEFAULT_FACTORY.create("other"), measurements); + assertTrue(filter.mightContainBatch(device, Collections.emptySet()).isEmpty()); + assertTrue( + BloomFilter.getEmptyBloomFilter(0.05, 1) + .mightContainBatch(device, Collections.singleton("")) + .isEmpty()); + } + } + + @Test + public void testBatchRejectsNullArguments() { + BloomFilter filter = BloomFilter.getEmptyBloomFilter(0.05, 10); + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create("root.d"); + assertThrows(NullPointerException.class, () -> filter.mightContainBatch(null, List.of())); + assertThrows(NullPointerException.class, () -> filter.mightContainBatch(null, List.of("s1"))); + assertThrows(NullPointerException.class, () -> filter.mightContainBatch(device, null)); + } + + @Test + public void testBatchChecksBothEmptyDevicePathForms() { + IDeviceID device = IDeviceID.Factory.DEFAULT_FACTORY.create(""); + List measurements = Arrays.asList("s1", "", null, "missing", "s1"); + BitSet expected = new BitSet(); + expected.set(0); + expected.set(1); + expected.set(4); + for (boolean useSeparator : new boolean[] {false, true}) { + BloomFilter filter = BloomFilter.getEmptyBloomFilter(0.01, 100); + for (String measurement : Arrays.asList("s1", "")) { + Path path = + useSeparator ? new FullPath(device, measurement) : new Path("", measurement, true); + filter.add(path); + } + assertEquals(expected, filter.mightContainBatch(device, measurements)); + } + } + + private static void assertBatchMatchesSingles( + BloomFilter filter, IDeviceID device, Collection measurements) { + BitSet expected = new BitSet(); + int index = 0; + for (String measurement : measurements) { + expected.set( + index++, measurement != null && filter.contains(new FullPath(device, measurement))); + } + assertEquals(expected, filter.mightContainBatch(device, measurements)); + } + + @Test + public void testHashByteSlices() { + byte[] data = new byte[65]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) (i * 31); + } + for (int offset = 0; offset <= data.length; offset++) { + for (int length = 0; length <= data.length - offset; length++) { + byte[] slice = Arrays.copyOfRange(data, offset, offset + length); + assertEquals( + Murmur128Hash.innerHash(slice, 0, slice.length, 5), + Murmur128Hash.innerHash(data, offset, length, 5)); + } + } + } + + @Test + public void testPrefixHashAtBlockBoundaries() { + int[] seeds = {5, 7, 11, 19, 31, 37, 43, 59}; + for (int i = 0; i < 48; i++) { + String prefix = "区域." + "p".repeat(i) + "."; + Murmur128Hash.PrefixHasher hasher = + new Murmur128Hash.PrefixHasher( + prefix.getBytes(StandardCharsets.UTF_8), seeds, seeds.length); + for (int j = 31; j >= 0; j--) { + String measurement = "é".repeat(j) + "温度🌡"; + hasher.setSuffix(measurement.getBytes(StandardCharsets.UTF_8)); + for (int k = 0; k < seeds.length; k++) { + assertEquals(hashUtf8(prefix + measurement, seeds[k]), hasher.hash(k)); + } + } + } + } + + @Test + public void testGrowingSuffixesWithLateSeedLookup() { + String prefix = "p".repeat(159) + "."; + int[] seeds = {5, 7}; + Murmur128Hash.PrefixHasher hasher = + new Murmur128Hash.PrefixHasher( + prefix.getBytes(StandardCharsets.UTF_8), seeds, seeds.length); + for (int length = 1; length <= 64; length++) { + String suffix = "s".repeat(length); + hasher.setSuffix(suffix.getBytes(StandardCharsets.UTF_8)); + assertEquals(hashUtf8(prefix + suffix, seeds[0]), hasher.hash(0)); + } + hasher.setSuffix(new byte[0]); + assertEquals(hashUtf8(prefix, seeds[1]), hasher.hash(1)); + assertEquals(hashUtf8(prefix, seeds[0]), hasher.hash(0)); + } + + private static int hashUtf8(String value, int seed) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + return (int) Murmur128Hash.innerHash(bytes, 0, bytes.length, seed); + } + + @Test + public void testBatchAgainstExistingFilter() { + // Generated by the snapshot writer for root.d., root.d.s1 and root.d.temp. + assumeTrue(Arrays.equals("root.d.".getBytes(), "root.d.".getBytes(StandardCharsets.US_ASCII))); + BloomFilter filter = + snapshotFilter(256, 4, 8, 51, 90, 96, 128, 157, 192, 193, 209, 229, 234, 237, 242, 245); + BitSet expected = new BitSet(); + expected.set(0, 3); + assertEquals( + expected, + filter.mightContainBatch( + IDeviceID.Factory.DEFAULT_FACTORY.create("root.d"), + Arrays.asList("", "s1", "temp", "absent"))); + } + + @Test + public void testBatchAgainstExistingMultiBlockFilter() { + // Snapshot bits for the time column, 温度 and load under the same multi-block UTF-8 prefix. + assumeTrue(StandardCharsets.UTF_8.equals(Charset.defaultCharset())); + BloomFilter filter = + snapshotFilter( + 1024, 9, 26, 228, 298, 337, 362, 384, 425, 440, 457, 470, 705, 836, 837, 938); + IDeviceID device = + IDeviceID.Factory.DEFAULT_FACTORY.create("root.factory.production_line_009.区域.station_43"); + BitSet expected = new BitSet(); + expected.set(0, 3); + assertEquals( + expected, filter.mightContainBatch(device, Arrays.asList("温度", "load", "", "absent"))); + } + + private static BloomFilter snapshotFilter(int size, int... setBits) { + BitSet bits = new BitSet(size); + for (int bit : setBits) { + bits.set(bit); + } + return BloomFilter.buildBloomFilter(bits.toByteArray(), size, 5); + } } diff --git a/skills/tsfile/references/java.md b/skills/tsfile/references/java.md index dfd10930c..647c1c49a 100644 --- a/skills/tsfile/references/java.md +++ b/skills/tsfile/references/java.md @@ -60,6 +60,19 @@ try (ITsFileTreeReader reader = } ``` +## Checking multiple measurements of one device + +Use `TsFileSequenceReader.readBloomFilter()` to obtain the file's +`org.apache.tsfile.utils.BloomFilter`. If it returns `null`, check the file's +metadata for all requested measurements. Otherwise, pass a non-null `IDeviceID` +and a non-null collection to `filter.mightContainBatch(device, measurements)`. +An individual `null` name has a clear bit. Bit positions in the returned +`BitSet` follow the collection's iteration order. A clear bit rules out the +corresponding measurement. A set bit requires checking the file's metadata. +Use an ordered collection when matching positions back to measurement names. +An empty measurement name probes the time column. For an empty device ID, the +lookup checks both supported path forms, for example `s1` and `.s1`. + ## Guidance - Prefer `Tablet` for batch writes and `TSRecord` for genuinely record-oriented