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