View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.filter;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Arrays;
23  import java.util.Comparator;
24  import java.util.TreeSet;
25  
26  import org.apache.hadoop.hbase.Cell;
27  import org.apache.hadoop.hbase.KeyValueUtil;
28  import org.apache.hadoop.hbase.classification.InterfaceAudience;
29  import org.apache.hadoop.hbase.classification.InterfaceStability;
30  import org.apache.hadoop.hbase.exceptions.DeserializationException;
31  import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
32  import org.apache.hadoop.hbase.util.ByteStringer;
33  import org.apache.hadoop.hbase.util.Bytes;
34  
35  import com.google.protobuf.InvalidProtocolBufferException;
36  
37  /**
38   * This filter is used for selecting only those keys with columns that matches
39   * a particular prefix. For example, if prefix is 'an', it will pass keys will
40   * columns like 'and', 'anti' but not keys with columns like 'ball', 'act'.
41   */
42  @InterfaceAudience.Public
43  @InterfaceStability.Stable
44  public class MultipleColumnPrefixFilter extends FilterBase {
45    protected byte [] hint = null;
46    protected TreeSet<byte []> sortedPrefixes = createTreeSet();
47    private final static int MAX_LOG_PREFIXES = 5;
48  
49    public MultipleColumnPrefixFilter(final byte [][] prefixes) {
50      if (prefixes != null) {
51        for (int i = 0; i < prefixes.length; i++) {
52          if (!sortedPrefixes.add(prefixes[i]))
53            throw new IllegalArgumentException ("prefixes must be distinct");
54        }
55      }
56    }
57  
58    public byte [][] getPrefix() {
59      int count = 0;
60      byte [][] temp = new byte [sortedPrefixes.size()][];
61      for (byte [] prefixes : sortedPrefixes) {
62        temp [count++] = prefixes;
63      }
64      return temp;
65    }
66  
67    @Override
68    public boolean filterRowKey(Cell cell) throws IOException {
69      // Impl in FilterBase might do unnecessary copy for Off heap backed Cells.
70      return false;
71    }
72  
73    @Override
74    public ReturnCode filterKeyValue(Cell kv) {
75      if (sortedPrefixes.size() == 0 || kv.getQualifierArray() == null) {
76        return ReturnCode.INCLUDE;
77      } else {
78        return filterColumn(kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength());
79      }
80    }
81  
82    public ReturnCode filterColumn(byte[] buffer, int qualifierOffset, int qualifierLength) {
83      byte [] qualifier = Arrays.copyOfRange(buffer, qualifierOffset,
84                                             qualifierLength + qualifierOffset);
85      TreeSet<byte []> lesserOrEqualPrefixes =
86        (TreeSet<byte []>) sortedPrefixes.headSet(qualifier, true);
87  
88      if (lesserOrEqualPrefixes.size() != 0) {
89        byte [] largestPrefixSmallerThanQualifier = lesserOrEqualPrefixes.last();
90        
91        if (Bytes.startsWith(qualifier, largestPrefixSmallerThanQualifier)) {
92          return ReturnCode.INCLUDE;
93        }
94        
95        if (lesserOrEqualPrefixes.size() == sortedPrefixes.size()) {
96          return ReturnCode.NEXT_ROW;
97        } else {
98          hint = sortedPrefixes.higher(largestPrefixSmallerThanQualifier);
99          return ReturnCode.SEEK_NEXT_USING_HINT;
100       }
101     } else {
102       hint = sortedPrefixes.first();
103       return ReturnCode.SEEK_NEXT_USING_HINT;
104     }
105   }
106 
107   public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
108     byte [][] prefixes = new byte [filterArguments.size()][];
109     for (int i = 0 ; i < filterArguments.size(); i++) {
110       byte [] columnPrefix = ParseFilter.removeQuotesFromByteArray(filterArguments.get(i));
111       prefixes[i] = columnPrefix;
112     }
113     return new MultipleColumnPrefixFilter(prefixes);
114   }
115 
116   /**
117    * @return The filter serialized using pb
118    */
119   public byte [] toByteArray() {
120     FilterProtos.MultipleColumnPrefixFilter.Builder builder =
121       FilterProtos.MultipleColumnPrefixFilter.newBuilder();
122     for (byte [] element : sortedPrefixes) {
123       if (element != null) builder.addSortedPrefixes(ByteStringer.wrap(element));
124     }
125     return builder.build().toByteArray();
126   }
127 
128   /**
129    * @param pbBytes A pb serialized {@link MultipleColumnPrefixFilter} instance
130    * @return An instance of {@link MultipleColumnPrefixFilter} made from <code>bytes</code>
131    * @throws DeserializationException
132    * @see #toByteArray
133    */
134   public static MultipleColumnPrefixFilter parseFrom(final byte [] pbBytes)
135   throws DeserializationException {
136     FilterProtos.MultipleColumnPrefixFilter proto;
137     try {
138       proto = FilterProtos.MultipleColumnPrefixFilter.parseFrom(pbBytes);
139     } catch (InvalidProtocolBufferException e) {
140       throw new DeserializationException(e);
141     }
142     int numPrefixes = proto.getSortedPrefixesCount();
143     byte [][] prefixes = new byte[numPrefixes][];
144     for (int i = 0; i < numPrefixes; ++i) {
145       prefixes[i] = proto.getSortedPrefixes(i).toByteArray();
146     }
147 
148     return new MultipleColumnPrefixFilter(prefixes);
149   }
150 
151   /**
152    * @param other
153    * @return true if and only if the fields of the filter that are serialized
154    * are equal to the corresponding fields in other.  Used for testing.
155    */
156   boolean areSerializedFieldsEqual(Filter o) {
157     if (o == this) return true;
158     if (!(o instanceof MultipleColumnPrefixFilter)) return false;
159 
160     MultipleColumnPrefixFilter other = (MultipleColumnPrefixFilter)o;
161     return this.sortedPrefixes.equals(other.sortedPrefixes);
162   }
163 
164   @Override
165   public Cell getNextCellHint(Cell cell) {
166     return KeyValueUtil.createFirstOnRow(
167       cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), cell.getFamilyArray(),
168       cell.getFamilyOffset(), cell.getFamilyLength(), hint, 0, hint.length);
169   }
170 
171   public TreeSet<byte []> createTreeSet() {
172     return new TreeSet<byte []>(new Comparator<Object>() {
173         @Override
174           public int compare (Object o1, Object o2) {
175           if (o1 == null || o2 == null)
176             throw new IllegalArgumentException ("prefixes can't be null");
177 
178           byte [] b1 = (byte []) o1;
179           byte [] b2 = (byte []) o2;
180           return Bytes.compareTo (b1, 0, b1.length, b2, 0, b2.length);
181         }
182       });
183   }
184 
185   @Override
186   public String toString() {
187     return toString(MAX_LOG_PREFIXES);
188   }
189 
190   protected String toString(int maxPrefixes) {
191     StringBuilder prefixes = new StringBuilder();
192 
193     int count = 0;
194     for (byte[] ba : this.sortedPrefixes) {
195       if (count >= maxPrefixes) {
196         break;
197       }
198       ++count;
199       prefixes.append(Bytes.toStringBinary(ba));
200       if (count < this.sortedPrefixes.size() && count < maxPrefixes) {
201         prefixes.append(", ");
202       }
203     }
204 
205     return String.format("%s (%d/%d): [%s]", this.getClass().getSimpleName(),
206         count, this.sortedPrefixes.size(), prefixes.toString());
207   }
208 }