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 Query
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 TimeRange tr = new TimeRange();
73    private boolean checkExistenceOnly = false;
74    private boolean closestRowBefore = false;
75    private Map<byte [], NavigableSet<byte []>> familyMap =
76      new TreeMap<byte [], NavigableSet<byte []>>(Bytes.BYTES_COMPARATOR);
77  
78    /**
79     * Create a Get operation for the specified row.
80     * <p>
81     * If no further operations are done, this will get the latest version of
82     * all columns in all families of the specified row.
83     * @param row row key
84     */
85    public Get(byte [] row) {
86      Mutation.checkRow(row);
87      this.row = row;
88    }
89  
90    public boolean isCheckExistenceOnly() {
91      return checkExistenceOnly;
92    }
93  
94    public void setCheckExistenceOnly(boolean checkExistenceOnly) {
95      this.checkExistenceOnly = checkExistenceOnly;
96    }
97  
98    public boolean isClosestRowBefore() {
99      return closestRowBefore;
100   }
101 
102   public void setClosestRowBefore(boolean closestRowBefore) {
103     this.closestRowBefore = closestRowBefore;
104   }
105 
106   /**
107    * Get all columns from the specified family.
108    * <p>
109    * Overrides previous calls to addColumn for this family.
110    * @param family family name
111    * @return the Get object
112    */
113   public Get addFamily(byte [] family) {
114     familyMap.remove(family);
115     familyMap.put(family, null);
116     return this;
117   }
118 
119   /**
120    * Get the column from the specific family with the specified qualifier.
121    * <p>
122    * Overrides previous calls to addFamily for this family.
123    * @param family family name
124    * @param qualifier column qualifier
125    * @return the Get objec
126    */
127   public Get addColumn(byte [] family, byte [] qualifier) {
128     NavigableSet<byte []> set = familyMap.get(family);
129     if(set == null) {
130       set = new TreeSet<byte []>(Bytes.BYTES_COMPARATOR);
131     }
132     if (qualifier == null) {
133       qualifier = HConstants.EMPTY_BYTE_ARRAY;
134     }
135     set.add(qualifier);
136     familyMap.put(family, set);
137     return this;
138   }
139 
140   /**
141    * Get versions of columns only within the specified timestamp range,
142    * [minStamp, maxStamp).
143    * @param minStamp minimum timestamp value, inclusive
144    * @param maxStamp maximum timestamp value, exclusive
145    * @throws IOException if invalid time range
146    * @return this for invocation chaining
147    */
148   public Get setTimeRange(long minStamp, long maxStamp)
149   throws IOException {
150     tr = new TimeRange(minStamp, maxStamp);
151     return this;
152   }
153 
154   /**
155    * Get versions of columns with the specified timestamp.
156    * @param timestamp version timestamp
157    * @return this for invocation chaining
158    */
159   public Get setTimeStamp(long timestamp) {
160     try {
161       tr = new TimeRange(timestamp, timestamp+1);
162     } catch(IOException e) {
163       // Will never happen
164     }
165     return this;
166   }
167 
168   /**
169    * Get all available versions.
170    * @return this for invocation chaining
171    */
172   public Get setMaxVersions() {
173     this.maxVersions = Integer.MAX_VALUE;
174     return this;
175   }
176 
177   /**
178    * Get up to the specified number of versions of each column.
179    * @param maxVersions maximum versions for each column
180    * @throws IOException if invalid number of versions
181    * @return this for invocation chaining
182    */
183   public Get setMaxVersions(int maxVersions) throws IOException {
184     if(maxVersions <= 0) {
185       throw new IOException("maxVersions must be positive");
186     }
187     this.maxVersions = maxVersions;
188     return this;
189   }
190 
191   /**
192    * Set the maximum number of values to return per row per Column Family
193    * @param limit the maximum number of values returned / row / CF
194    * @return this for invocation chaining
195    */
196   public Get setMaxResultsPerColumnFamily(int limit) {
197     this.storeLimit = limit;
198     return this;
199   }
200 
201   /**
202    * Set offset for the row per Column Family. This offset is only within a particular row/CF
203    * combination. It gets reset back to zero when we move to the next row or CF.
204    * @param offset is the number of kvs that will be skipped.
205    * @return this for invocation chaining
206    */
207   public Get setRowOffsetPerColumnFamily(int offset) {
208     this.storeOffset = offset;
209     return this;
210   }
211 
212   @Override
213   public Get setFilter(Filter filter) {
214     super.setFilter(filter);
215     return this;
216   }
217 
218   /* Accessors */
219 
220   /**
221    * Set whether blocks should be cached for this Get.
222    * <p>
223    * This is true by default.  When true, default settings of the table and
224    * family are used (this will never override caching blocks if the block
225    * cache is disabled for that family or entirely).
226    *
227    * @param cacheBlocks if false, default settings are overridden and blocks
228    * will not be cached
229    */
230   public void setCacheBlocks(boolean cacheBlocks) {
231     this.cacheBlocks = cacheBlocks;
232   }
233 
234   /**
235    * Get whether blocks should be cached for this Get.
236    * @return true if default caching should be used, false if blocks should not
237    * be cached
238    */
239   public boolean getCacheBlocks() {
240     return cacheBlocks;
241   }
242 
243   /**
244    * Method for retrieving the get's row
245    * @return row
246    */
247   public byte [] getRow() {
248     return this.row;
249   }
250 
251   /**
252    * Method for retrieving the get's maximum number of version
253    * @return the maximum number of version to fetch for this get
254    */
255   public int getMaxVersions() {
256     return this.maxVersions;
257   }
258 
259   /**
260    * Method for retrieving the get's maximum number of values
261    * to return per Column Family
262    * @return the maximum number of values to fetch per CF
263    */
264   public int getMaxResultsPerColumnFamily() {
265     return this.storeLimit;
266   }
267 
268   /**
269    * Method for retrieving the get's offset per row per column
270    * family (#kvs to be skipped)
271    * @return the row offset
272    */
273   public int getRowOffsetPerColumnFamily() {
274     return this.storeOffset;
275   }
276 
277   /**
278    * Method for retrieving the get's TimeRange
279    * @return timeRange
280    */
281   public TimeRange getTimeRange() {
282     return this.tr;
283   }
284 
285   /**
286    * Method for retrieving the keys in the familyMap
287    * @return keys in the current familyMap
288    */
289   public Set<byte[]> familySet() {
290     return this.familyMap.keySet();
291   }
292 
293   /**
294    * Method for retrieving the number of families to get from
295    * @return number of families
296    */
297   public int numFamilies() {
298     return this.familyMap.size();
299   }
300 
301   /**
302    * Method for checking if any families have been inserted into this Get
303    * @return true if familyMap is non empty false otherwise
304    */
305   public boolean hasFamilies() {
306     return !this.familyMap.isEmpty();
307   }
308 
309   /**
310    * Method for retrieving the get's familyMap
311    * @return familyMap
312    */
313   public Map<byte[],NavigableSet<byte[]>> getFamilyMap() {
314     return this.familyMap;
315   }
316 
317   /**
318    * Compile the table and column family (i.e. schema) information
319    * into a String. Useful for parsing and aggregation by debugging,
320    * logging, and administration tools.
321    * @return Map
322    */
323   @Override
324   public Map<String, Object> getFingerprint() {
325     Map<String, Object> map = new HashMap<String, Object>();
326     List<String> families = new ArrayList<String>();
327     map.put("families", families);
328     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
329       this.familyMap.entrySet()) {
330       families.add(Bytes.toStringBinary(entry.getKey()));
331     }
332     return map;
333   }
334 
335   /**
336    * Compile the details beyond the scope of getFingerprint (row, columns,
337    * timestamps, etc.) into a Map along with the fingerprinted information.
338    * Useful for debugging, logging, and administration tools.
339    * @param maxCols a limit on the number of columns output prior to truncation
340    * @return Map
341    */
342   @Override
343   public Map<String, Object> toMap(int maxCols) {
344     // we start with the fingerprint map and build on top of it.
345     Map<String, Object> map = getFingerprint();
346     // replace the fingerprint's simple list of families with a 
347     // map from column families to lists of qualifiers and kv details
348     Map<String, List<String>> columns = new HashMap<String, List<String>>();
349     map.put("families", columns);
350     // add scalar information first
351     map.put("row", Bytes.toStringBinary(this.row));
352     map.put("maxVersions", this.maxVersions);
353     map.put("cacheBlocks", this.cacheBlocks);
354     List<Long> timeRange = new ArrayList<Long>();
355     timeRange.add(this.tr.getMin());
356     timeRange.add(this.tr.getMax());
357     map.put("timeRange", timeRange);
358     int colCount = 0;
359     // iterate through affected families and add details
360     for (Map.Entry<byte [], NavigableSet<byte[]>> entry :
361       this.familyMap.entrySet()) {
362       List<String> familyList = new ArrayList<String>();
363       columns.put(Bytes.toStringBinary(entry.getKey()), familyList);
364       if(entry.getValue() == null) {
365         colCount++;
366         --maxCols;
367         familyList.add("ALL");
368       } else {
369         colCount += entry.getValue().size();
370         if (maxCols <= 0) {
371           continue;
372         }
373         for (byte [] column : entry.getValue()) {
374           if (--maxCols <= 0) {
375             continue;
376           }
377           familyList.add(Bytes.toStringBinary(column));
378         }
379       }   
380     }   
381     map.put("totalColumns", colCount);
382     if (this.filter != null) {
383       map.put("filter", this.filter.toString());
384     }
385     // add the id if set
386     if (getId() != null) {
387       map.put("id", getId());
388     }
389     return map;
390   }
391 
392   //Row
393   @Override
394   public int compareTo(Row other) {
395     // TODO: This is wrong.  Can't have two gets the same just because on same row.
396     return Bytes.compareTo(this.getRow(), other.getRow());
397   }
398 
399   @Override
400   public int hashCode() {
401     // TODO: This is wrong.  Can't have two gets the same just because on same row.  But it
402     // matches how equals works currently and gets rid of the findbugs warning.
403     return Bytes.hashCode(this.getRow());
404   }
405 
406   @Override
407   public boolean equals(Object obj) {
408     if (this == obj) {
409       return true;
410     }
411     if (obj == null || getClass() != obj.getClass()) {
412       return false;
413     }
414     Row other = (Row) obj;
415     // TODO: This is wrong.  Can't have two gets the same just because on same row.
416     return compareTo(other) == 0;
417   }
418 }