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