Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
import org.apache.parquet.schema.PrimitiveType;
import org.slf4j.Logger;

@Parameters(commandDescription = "Check bloom filters for a Parquet column")
@Parameters(commandDescription = "Show bloom filter metadata or check values for a Parquet column")
public class ShowBloomFilterCommand extends BaseCommand {

public ShowBloomFilterCommand(Logger console) {
Expand All @@ -51,46 +51,49 @@ public ShowBloomFilterCommand(Logger console) {

@Parameter(
names = {"-c", "--column"},
description = "Check the bloom filter indexes for the given column",
required = true)
description = "Show or check the bloom filter for the given column only")
String columnPath;

@Parameter(
names = {"-v", "--values"},
description = "Check if the given values match bloom filter",
required = true)
description = "Check if the given values match bloom filter (requires --column)")
List<String> testValues;

@Override
@SuppressWarnings("unchecked")
public int run() throws IOException {
Preconditions.checkArgument(file != null, "A Parquet file is required.");
Preconditions.checkArgument(columnPath != null || testValues == null, "A column is required to check values.");

try (ParquetFileReader reader = createParquetFileReader(file)) {
MessageType schema = reader.getFileMetaData().getSchema();
PrimitiveType type = Util.primitive(columnPath, schema);
PrimitiveType type = columnPath == null ? null : Util.primitive(columnPath, schema);

int rowGroupIndex = 0;
for (BlockMetaData block : reader.getFooter().getBlocks()) {
console.info(String.format(
"\nRow group %d: \n%s", rowGroupIndex, new TextStringBuilder(80).appendPadding(80, '-')));

Optional<ColumnChunkMetaData> maybeColumnMeta = block.getColumns().stream()
.filter(c -> columnPath.equals(c.getPath().toDotString()))
.findFirst();
if (!maybeColumnMeta.isPresent()) {
console.info("column {} doesn't exist.", columnPath);
if (testValues == null) {
showMetadata(reader, block);
} else {
BloomFilterReader bloomFilterReader = reader.getBloomFilterDataReader(block);
BloomFilter bloomFilter = bloomFilterReader.readBloomFilter(maybeColumnMeta.get());
if (bloomFilter == null) {
console.info("column {} has no bloom filter", columnPath);
Optional<ColumnChunkMetaData> maybeColumnMeta = block.getColumns().stream()
.filter(c -> columnPath.equals(c.getPath().toDotString()))
.findFirst();
if (!maybeColumnMeta.isPresent()) {
console.info("column {} doesn't exist.", columnPath);
} else {
for (String value : testValues) {
if (bloomFilter.findHash(bloomFilter.hash(getOriginalType(value, type)))) {
console.info("value {} maybe exists.", value);
} else {
console.info("value {} NOT exists.", value);
BloomFilterReader bloomFilterReader = reader.getBloomFilterDataReader(block);
BloomFilter bloomFilter = bloomFilterReader.readBloomFilter(maybeColumnMeta.get());
if (bloomFilter == null) {
console.info("column {} has no bloom filter", columnPath);
} else {
for (String value : testValues) {
if (bloomFilter.findHash(bloomFilter.hash(getOriginalType(value, type)))) {
console.info("value {} maybe exists.", value);
} else {
console.info("value {} NOT exists.", value);
}
}
}
}
Expand All @@ -101,6 +104,26 @@ public int run() throws IOException {
return 0;
}

private void showMetadata(ParquetFileReader reader, BlockMetaData block) throws IOException {
BloomFilterReader bloomFilterReader = reader.getBloomFilterDataReader(block);
for (ColumnChunkMetaData column : block.getColumns()) {
String path = column.getPath().toDotString();
if (columnPath != null && !columnPath.equals(path)) {
continue;
}
console.info("bloom filter for column {}:", path);
BloomFilter bloomFilter = bloomFilterReader.readBloomFilter(column);
if (bloomFilter == null) {
console.info("NONE");
} else {
console.info("Hash strategy: {}", bloomFilter.getHashStrategy());
console.info("Algorithm: {}", bloomFilter.getAlgorithm());
console.info("Compression: {}", bloomFilter.getCompression());
console.info("Bitset size: {}", bloomFilter.getBitsetSize());
}
}
}

private Object getOriginalType(String value, PrimitiveType type) {
switch (type.getPrimitiveTypeName()) {
case BINARY:
Expand All @@ -121,6 +144,11 @@ private Object getOriginalType(String value, PrimitiveType type) {
@Override
public List<String> getExamples() {
return Arrays.asList(
"# Show bloom filter for column 'col' from a Parquet file", "-c col -v 1,2,3 -i sample.parquet");
"# Show bloom filter metadata for all columns",
"sample.parquet",
"# Show bloom filter metadata for column 'col'",
"-c col sample.parquet",
"# Check values against the bloom filter for column 'col'",
"-c col -v 1,2,3 sample.parquet");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.parquet.cli;

import static org.assertj.core.api.Assertions.assertThat;

import java.nio.file.Path;
import org.apache.parquet.example.data.Group;
import org.apache.parquet.example.data.simple.SimpleGroupFactory;
import org.apache.parquet.hadoop.ParquetWriter;
import org.apache.parquet.hadoop.example.ExampleParquetWriter;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.MessageTypeParser;
import org.junit.jupiter.api.Test;

class BloomFilterCliTest extends CliTestBase {

private static final String BLOOM_METADATA =
"Hash strategy: xxhash\nAlgorithm: block\nCompression: uncompressed\nBitset size: 1024";

@Test
void showsMetadataForEveryColumnAndRowGroup() throws Exception {
CliResult result = cli("bloom-filter", writeBloomFile().toString());

assertThat(result.exitCode()).as(result.output()).isZero();
String columns = "bloom filter for column id:\nNONE\nbloom filter for column uuid:\n"
+ BLOOM_METADATA
+ "\nbloom filter for column user.name:\n"
+ BLOOM_METADATA;
assertThat(result.output())
.isEqualTo(rowGroup(0, columns) + "\n" + rowGroup(1, columns) + "\n" + rowGroup(2, columns));
}

@Test
void showsMetadataForSelectedNestedColumn() throws Exception {
CliResult result =
cli("bloom-filter", "--column", "user.name", writeBloomFile().toString());

assertThat(result.exitCode()).as(result.output()).isZero();
String column = "bloom filter for column user.name:\n" + BLOOM_METADATA;
assertThat(result.output())
.isEqualTo(rowGroup(0, column) + "\n" + rowGroup(1, column) + "\n" + rowGroup(2, column));
}

@Test
void showsNoneForColumnWithoutBloomFilter() throws Exception {
CliResult result = cli("bloom-filter", "-c", "id", writeBloomFile().toString());

assertThat(result.exitCode()).as(result.output()).isZero();
String column = "bloom filter for column id:\nNONE";
assertThat(result.output())
.isEqualTo(rowGroup(0, column) + "\n" + rowGroup(1, column) + "\n" + rowGroup(2, column));
}

@Test
void keepsValueMembershipChecks() throws Exception {
CliResult result = cli(
"bloom-filter",
"-c",
"uuid",
"-v",
"record-0,missing",
writeBloomFile().toString());

assertThat(result.exitCode()).as(result.output()).isZero();
assertThat(result.output())
.isEqualTo(rowGroup(0, "value record-0 maybe exists.\nvalue missing NOT exists.")
+ "\n"
+ rowGroup(1, "value record-0 NOT exists.\nvalue missing NOT exists.")
+ "\n"
+ rowGroup(2, "value record-0 NOT exists.\nvalue missing NOT exists."));
}

@Test
void requiresColumnWhenCheckingValues() throws Exception {
CliResult result =
cli("bloom-filter", "-v", "record-0", writeBloomFile().toString());

assertThat(result.exitCode()).isEqualTo(1);
assertThat(result.output()).contains("A column is required to check values.");
}

@Test
void rejectsUnknownColumn() throws Exception {
CliResult result = cli("bloom-filter", "-c", "missing", writeBloomFile().toString());

assertThat(result.exitCode()).isEqualTo(1);
assertThat(result.output()).contains("Schema doesn't have column: missing");
}

private Path writeBloomFile() throws Exception {
Path file = getTempFolder().toPath().resolve("input with spaces.parquet");
MessageType schema = MessageTypeParser.parseMessageType("message record {"
+ " required int32 id; required binary uuid (STRING);"
+ " required group user { required binary name (STRING); } }");
SimpleGroupFactory factory = new SimpleGroupFactory(schema);
try (ParquetWriter<Group> writer = ExampleParquetWriter.builder(new org.apache.hadoop.fs.Path(file.toUri()))
.withType(schema)
.withDictionaryEncoding(false)
.withBloomFilterEnabled("uuid", true)
.withBloomFilterEnabled("user.name", true)
.withMaxBloomFilterBytes(1024)
.withRowGroupRowCountLimit(2)
.withMinRowCountForPageSizeCheck(1)
.withMaxRowCountForPageSizeCheck(1)
.build()) {
for (int i = 0; i < 5; i++) {
Group row = factory.newGroup().append("id", i).append("uuid", "record-" + i);
row.addGroup("user").append("name", "name-" + i);
writer.write(row);
}
}
return file;
}

private static String rowGroup(int index, String contents) {
return "\nRow group " + index + ": \n" + "-".repeat(80) + "\n" + contents;
}
}