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.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.Comparator;
23  import java.util.TreeSet;
24  
25  import org.apache.hadoop.classification.InterfaceAudience;
26  import org.apache.hadoop.classification.InterfaceStability;
27  import org.apache.hadoop.hbase.Cell;
28  import org.apache.hadoop.hbase.KeyValueUtil;
29  import org.apache.hadoop.hbase.exceptions.DeserializationException;
30  import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
31  import org.apache.hadoop.hbase.util.ByteStringer;
32  import org.apache.hadoop.hbase.util.Bytes;
33  
34  import com.google.protobuf.InvalidProtocolBufferException;
35  
36  /**
37   * This filter is used for selecting only those keys with columns that matches
38   * a particular prefix. For example, if prefix is 'an', it will pass keys will
39   * columns like 'and', 'anti' but not keys with columns like 'ball', 'act'.
40   */
41  @InterfaceAudience.Public
42  @InterfaceStability.Stable
43  public class MultipleColumnPrefixFilter extends FilterBase {
44    protected byte [] hint = null;
45    protected TreeSet<byte []> sortedPrefixes = createTreeSet();
46    private final static int MAX_LOG_PREFIXES = 5;
47  
48    public MultipleColumnPrefixFilter(final byte [][] prefixes) {
49      if (prefixes != null) {
50        for (int i = 0; i < prefixes.length; i++) {
51          if (!sortedPrefixes.add(prefixes[i]))
52            throw new IllegalArgumentException ("prefixes must be distinct");
53        }
54      }
55    }
56  
57    public byte [][] getPrefix() {
58      int count = 0;
59      byte [][] temp = new byte [sortedPrefixes.size()][];
60      for (byte [] prefixes : sortedPrefixes) {
61        temp [count++] = prefixes;
62      }
63      return temp;
64    }
65  
66    @Override
67    public ReturnCode filterKeyValue(Cell kv) {
68      if (sortedPrefixes.size() == 0 || kv.getQualifierArray() == null) {
69        return ReturnCode.INCLUDE;
70      } else {
71        return filterColumn(kv.getQualifierArray(), kv.getQualifierOffset(), kv.getQualifierLength());
72      }
73    }
74  
75    public ReturnCode filterColumn(byte[] buffer, int qualifierOffset, int qualifierLength) {
76      byte [] qualifier = Arrays.copyOfRange(buffer, qualifierOffset,
77                                             qualifierLength + qualifierOffset);
78      TreeSet<byte []> lesserOrEqualPrefixes =
79        (TreeSet<byte []>) sortedPrefixes.headSet(qualifier, true);
80  
81      if (lesserOrEqualPrefixes.size() != 0) {
82        byte [] largestPrefixSmallerThanQualifier = lesserOrEqualPrefixes.last();
83        
84        if (Bytes.startsWith(qualifier, largestPrefixSmallerThanQualifier)) {
85          return ReturnCode.INCLUDE;
86        }
87        
88        if (lesserOrEqualPrefixes.size() == sortedPrefixes.size()) {
89          return ReturnCode.NEXT_ROW;
90        } else {
91          hint = sortedPrefixes.higher(largestPrefixSmallerThanQualifier);
92          return ReturnCode.SEEK_NEXT_USING_HINT;
93        }
94      } else {
95        hint = sortedPrefixes.first();
96        return ReturnCode.SEEK_NEXT_USING_HINT;
97      }
98    }
99  
100   public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
101     byte [][] prefixes = new byte [filterArguments.size()][];
102     for (int i = 0 ; i < filterArguments.size(); i++) {
103       byte [] columnPrefix = ParseFilter.removeQuotesFromByteArray(filterArguments.get(i));
104       prefixes[i] = columnPrefix;
105     }
106     return new MultipleColumnPrefixFilter(prefixes);
107   }
108 
109   /**
110    * @return The filter serialized using pb
111    */
112   public byte [] toByteArray() {
113     FilterProtos.MultipleColumnPrefixFilter.Builder builder =
114       FilterProtos.MultipleColumnPrefixFilter.newBuilder();
115     for (byte [] element : sortedPrefixes) {
116       if (element != null) builder.addSortedPrefixes(ByteStringer.wrap(element));
117     }
118     return builder.build().toByteArray();
119   }
120 
121   /**
122    * @param pbBytes A pb serialized {@link MultipleColumnPrefixFilter} instance
123    * @return An instance of {@link MultipleColumnPrefixFilter} made from <code>bytes</code>
124    * @throws DeserializationException
125    * @see #toByteArray
126    */
127   public static MultipleColumnPrefixFilter parseFrom(final byte [] pbBytes)
128   throws DeserializationException {
129     FilterProtos.MultipleColumnPrefixFilter proto;
130     try {
131       proto = FilterProtos.MultipleColumnPrefixFilter.parseFrom(pbBytes);
132     } catch (InvalidProtocolBufferException e) {
133       throw new DeserializationException(e);
134     }
135     int numPrefixes = proto.getSortedPrefixesCount();
136     byte [][] prefixes = new byte[numPrefixes][];
137     for (int i = 0; i < numPrefixes; ++i) {
138       prefixes[i] = proto.getSortedPrefixes(i).toByteArray();
139     }
140 
141     return new MultipleColumnPrefixFilter(prefixes);
142   }
143 
144   /**
145    * @param other
146    * @return true if and only if the fields of the filter that are serialized
147    * are equal to the corresponding fields in other.  Used for testing.
148    */
149   boolean areSerializedFieldsEqual(Filter o) {
150     if (o == this) return true;
151     if (!(o instanceof MultipleColumnPrefixFilter)) return false;
152 
153     MultipleColumnPrefixFilter other = (MultipleColumnPrefixFilter)o;
154     return this.sortedPrefixes.equals(other.sortedPrefixes);
155   }
156 
157   @Override
158   public Cell getNextCellHint(Cell cell) {
159     return KeyValueUtil.createFirstOnRow(
160       cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), cell.getFamilyArray(),
161       cell.getFamilyOffset(), cell.getFamilyLength(), hint, 0, hint.length);
162   }
163 
164   public TreeSet<byte []> createTreeSet() {
165     return new TreeSet<byte []>(new Comparator<Object>() {
166         @Override
167           public int compare (Object o1, Object o2) {
168           if (o1 == null || o2 == null)
169             throw new IllegalArgumentException ("prefixes can't be null");
170 
171           byte [] b1 = (byte []) o1;
172           byte [] b2 = (byte []) o2;
173           return Bytes.compareTo (b1, 0, b1.length, b2, 0, b2.length);
174         }
175       });
176   }
177 
178   @Override
179   public String toString() {
180     return toString(MAX_LOG_PREFIXES);
181   }
182 
183   protected String toString(int maxPrefixes) {
184     StringBuilder prefixes = new StringBuilder();
185 
186     int count = 0;
187     for (byte[] ba : this.sortedPrefixes) {
188       if (count >= maxPrefixes) {
189         break;
190       }
191       ++count;
192       prefixes.append(Bytes.toStringBinary(ba));
193       if (count < this.sortedPrefixes.size() && count < maxPrefixes) {
194         prefixes.append(", ");
195       }
196     }
197 
198     return String.format("%s (%d/%d): [%s]", this.getClass().getSimpleName(),
199         count, this.sortedPrefixes.size(), prefixes.toString());
200   }
201 }