View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.client;
20  
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.HashMap;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.NavigableSet;
28  import java.util.Set;
29  import java.util.TreeMap;
30  import java.util.TreeSet;
31  
32  import org.apache.hadoop.classification.InterfaceAudience;
33  import org.apache.hadoop.classification.InterfaceStability;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.filter.Filter;
36  import org.apache.hadoop.hbase.io.TimeRange;
37  import org.apache.hadoop.hbase.util.Bytes;
38  
39  /**
40   * Used to perform Get operations on a single row.
41   * <p>
42   * To get everything for a row, instantiate a Get object with the row to get.
43   * To further narrow the scope of what to Get, use the methods below.
44   * <p>
45   * To get all columns from specific families, execute {@link #addFamily(byte[]) addFamily}
46   * for each family to retrieve.
47   * <p>
48   * To get specific columns, execute {@link #addColumn(byte[], byte[]) addColumn}
49   * for each column to retrieve.
50   * <p>
51   * To only retrieve columns within a specific range of version timestamps,
52   * execute {@link #setTimeRange(long, long) setTimeRange}.
53   * <p>
54   * To only retrieve columns with a specific timestamp, execute
55   * {@link #setTimeStamp(long) setTimestamp}.
56   * <p>
57   * To limit the number of versions of each column to be returned, execute
58   * {@link #setMaxVersions(int) setMaxVersions}.
59   * <p>
60   * To add a filter, call {@link #setFilter(Filter) setFilter}.
61   */
62  @InterfaceAudience.Public
63  @InterfaceStability.Stable
64  public class Get extends OperationWithAttributes
65    implements Row, Comparable<Row> {
66  
67    private byte [] row = null;
68    private int maxVersions = 1;
69    private boolean cacheBlocks = true;
70    private int storeLimit = -1;
71    private int storeOffset = 0;
72    private Filter filter = null;
73    private TimeRange tr = new TimeRange();
74    private boolean checkExistenceOnly = false;
75    private boolean closestRowBefore = false;
76    private Map<byte [], NavigableSet<byte []>> familyMap =
77      new TreeMap<byte [], NavigableSet<byte []>>(Bytes.BYTES_COMPARATOR);
78  
79    /**
80     * Create a Get operation for the specified row.
81     * <p>
82     * If no further operations are done, this will get the latest version of
83     * all columns in all families of the specified row.
84     * @param row row key
85     */
86    public Get(byte [] row) {
87      Mutation.checkRow(row);
88      this.row = row;
89    }
90  
91    public boolean isCheckExistenceOnly() {
92      return checkExistenceOnly;
93    }
94  
95    public void setCheckExistenceOnly(boolean checkExistenceOnly) {
96      this.checkExistenceOnly = checkExistenceOnly;
97    }
98  
99    public boolean isClosestRowBefore() {
100     return closestRowBefore;
101   }
102 
103   public void setClosestRowBefore(boolean closestRowBefore) {
104     this.closestRowBefore = closestRowBefore;
105   }
106 
107   /**
108    * Get all columns from the specified family.
109    * <p>
110    * Overrides previous calls to addColumn for this family.
111    * @param family family name
112    * @return the Get object
113    */
114   public Get addFamily(byte [] family) {
115     familyMap.remove(family);
116     familyMap.put(family, null);
117     return this;
118   }
119 
120   /**
121    * Get the column from the specific family with the specified qualifier.
122    * <p>
123    * Overrides previous calls to addFamily for this family.
124    * @param family family name
125    * @param qualifier column qualifier
126    * @return the Get objec
127    */
128   public Get addColumn(byte [] family, byte [] qualifier) {
129     NavigableSet<byte []> set = familyMap.get(family);
130     if(set == null) {
131       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
132     }
133     if (qualifier == null) {
134       qualifier = HConstants.EMPTY_BYTE_ARRAY;
135     }
136     set.add(qualifier);
137     familyMap.put(family, set);
138     return this;
139   }
140 
141   /**
142    * Get versions of columns only within the specified timestamp range,
143    * [minStamp, maxStamp).
144    * @param minStamp minimum timestamp value, inclusive
145    * @param maxStamp maximum timestamp value, exclusive
146    * @throws IOException if invalid time range
147    * @return this for invocation chaining
148    */
149   public Get setTimeRange(long minStamp, long maxStamp)
150   throws IOException {
151     tr = new TimeRange(minStamp, maxStamp);
152     return this;
153   }
154 
155   /**
156    * Get versions of columns with the specified timestamp.
157    * @param timestamp version timestamp
158    * @return this for invocation chaining
159    */
160   public Get setTimeStamp(long timestamp) {
161     try {
162       tr = new TimeRange(timestamp, timestamp+1);
163     } catch(IOException e) {
164       // Will never happen
165     }
166     return this;
167   }
168 
169   /**
170    * Get all available versions.
171    * @return this for invocation chaining
172    */
173   public Get setMaxVersions() {
174     this.maxVersions = Integer.MAX_VALUE;
175     return this;
176   }
177 
178   /**
179    * Get up to the specified number of versions of each column.
180    * @param maxVersions maximum versions for each column
181    * @throws IOException if invalid number of versions
182    * @return this for invocation chaining
183    */
184   public Get setMaxVersions(int maxVersions) throws IOException {
185     if(maxVersions <= 0) {
186       throw new IOException("maxVersions must be positive");
187     }
188     this.maxVersions = maxVersions;
189     return this;
190   }
191 
192   /**
193    * Set the maximum number of values to return per row per Column Family
194    * @param limit the maximum number of values returned / row / CF
195    * @return this for invocation chaining
196    */
197   public Get setMaxResultsPerColumnFamily(int limit) {
198     this.storeLimit = limit;
199     return this;
200   }
201 
202   /**
203    * Set offset for the row per Column Family. This offset is only within a particular row/CF
204    * combination. It gets reset back to zero when we move to the next row or CF.
205    * @param offset is the number of kvs that will be skipped.
206    * @return this for invocation chaining
207    */
208   public Get setRowOffsetPerColumnFamily(int offset) {
209     this.storeOffset = offset;
210     return this;
211   }
212 
213   /**
214    * Apply the specified server-side filter when performing the Get.
215    * Only {@link Filter#filterKeyValue(Cell)} is called AFTER all tests
216    * for ttl, column match, deletes and max versions have been run.
217    * @param filter filter to run on the server
218    * @return this for invocation chaining
219    */
220   public Get setFilter(Filter filter) {
221     this.filter = filter;
222     return this;
223   }
224 
225   /* Accessors */
226 
227   /**
228    * @return Filter
229    */
230   public Filter getFilter() {
231     return this.filter;
232   }
233 
234   /**
235    * Set whether blocks should be cached for this Get.
236    * <p>
237    * This is true by default.  When true, default settings of the table and
238    * family are used (this will never override caching blocks if the block
239    * cache is disabled for that family or entirely).
240    *
241    * @param cacheBlocks if false, default settings are overridden and blocks
242    * will not be cached
243    */
244   public void setCacheBlocks(boolean cacheBlocks) {
245     this.cacheBlocks = cacheBlocks;
246   }
247 
248   /**
249    * Get whether blocks should be cached for this Get.
250    * @return true if default caching should be used, false if blocks should not
251    * be cached
252    */
253   public boolean getCacheBlocks() {
254     return cacheBlocks;
255   }
256 
257   /**
258    * Method for retrieving the get's row
259    * @return row
260    */
261   public byte [] getRow() {
262     return this.row;
263   }
264 
265   /**
266    * Method for retrieving the get's maximum number of version
267    * @return the maximum number of version to fetch for this get
268    */
269   public int getMaxVersions() {
270     return this.maxVersions;
271   }
272 
273   /**
274    * Method for retrieving the get's maximum number of values
275    * to return per Column Family
276    * @return the maximum number of values to fetch per CF
277    */
278   public int getMaxResultsPerColumnFamily() {
279     return this.storeLimit;
280   }
281 
282   /**
283    * Method for retrieving the get's offset per row per column
284    * family (#kvs to be skipped)
285    * @return the row offset
286    */
287   public int getRowOffsetPerColumnFamily() {
288     return this.storeOffset;
289   }
290 
291   /**
292    * Method for retrieving the get's TimeRange
293    * @return timeRange
294    */
295   public TimeRange getTimeRange() {
296     return this.tr;
297   }
298 
299   /**
300    * Method for retrieving the keys in the familyMap
301    * @return keys in the current familyMap
302    */
303   public Set<byte[]> familySet() {
304     return this.familyMap.keySet();
305   }
306 
307   /**
308    * Method for retrieving the number of families to get from
309    * @return number of families
310    */
311   public int numFamilies() {
312     return this.familyMap.size();
313   }
314 
315   /**
316    * Method for checking if any families have been inserted into this Get
317    * @return true if familyMap is non empty false otherwise
318    */
319   public boolean hasFamilies() {
320     return !this.familyMap.isEmpty();
321   }
322 
323   /**
324    * Method for retrieving the get's familyMap
325    * @return familyMap
326    */
327   public Map<byte[],NavigableSet<byte[]>> getFamilyMap() {
328     return this.familyMap;
329   }
330 
331   /**
332    * Compile the table and column family (i.e. schema) information
333    * into a String. Useful for parsing and aggregation by debugging,
334    * logging, and administration tools.
335    * @return Map
336    */
337   @Override
338   public Map<String, Object> getFingerprint() {
339     Map<String, Object> map = new HashMap<String, Object>();
340     List<String> families = new ArrayList<String>();
341     map.put("families", families);
342     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
343       this.familyMap.entrySet()) {
344       families.add(Bytes.toStringBinary(entry.getKey()));
345     }
346     return map;
347   }
348 
349   /**
350    * Compile the details beyond the scope of getFingerprint (row, columns,
351    * timestamps, etc.) into a Map along with the fingerprinted information.
352    * Useful for debugging, logging, and administration tools.
353    * @param maxCols a limit on the number of columns output prior to truncation
354    * @return Map
355    */
356   @Override
357   public Map<String, Object> toMap(int maxCols) {
358     // we start with the fingerprint map and build on top of it.
359     Map<String, Object> map = getFingerprint();
360     // replace the fingerprint's simple list of families with a 
361     // map from column families to lists of qualifiers and kv details
362     Map<String, List<String>> columns = new HashMap<String, List<String>>();
363     map.put("families", columns);
364     // add scalar information first
365     map.put("row", Bytes.toStringBinary(this.row));
366     map.put("maxVersions", this.maxVersions);
367     map.put("cacheBlocks", this.cacheBlocks);
368     List<Long> timeRange = new ArrayList<Long>();
369     timeRange.add(this.tr.getMin());
370     timeRange.add(this.tr.getMax());
371     map.put("timeRange", timeRange);
372     int colCount = 0;
373     // iterate through affected families and add details
374     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
375       this.familyMap.entrySet()) {
376       List<String> familyList = new ArrayList<String>();
377       columns.put(Bytes.toStringBinary(entry.getKey()), familyList);
378       if(entry.getValue() == null) {
379         colCount++;
380         --maxCols;
381         familyList.add("ALL");
382       } else {
383         colCount += entry.getValue().size();
384         if (maxCols <= 0) {
385           continue;
386         }
387         for (byte [] column : entry.getValue()) {
388           if (--maxCols <= 0) {
389             continue;
390           }
391           familyList.add(Bytes.toStringBinary(column));
392         }
393       }   
394     }   
395     map.put("totalColumns", colCount);
396     if (this.filter != null) {
397       map.put("filter", this.filter.toString());
398     }
399     // add the id if set
400     if (getId() != null) {
401       map.put("id", getId());
402     }
403     return map;
404   }
405 
406   //Row
407   @Override
408   public int compareTo(Row other) {
409     // TODO: This is wrong.  Can't have two gets the same just because on same row.
410     return Bytes.compareTo(this.getRow(), other.getRow());
411   }
412 
413   @Override
414   public int hashCode() {
415     // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
416     // matches how equals works currently and gets rid of the findbugs warning.
417     return Bytes.hashCode(this.getRow());
418   }
419 
420   @Override
421   public boolean equals(Object obj) {
422     if (this == obj) {
423       return true;
424     }
425     if (obj == null || getClass() != obj.getClass()) {
426       return false;
427     }
428     Row other = (Row) obj;
429     // TODO: This is wrong.  Can't have two gets the same just because on same row.
430     return compareTo(other) == 0;
431   }
432 }