Get records based on Rowkey and ColumnFamily - java

Is it possible to read data from HBase based on rowKey and columnFamily. Currently I access records by rowkey by this code:
HTable table = new HTable(conf, "tablename");
Get get = new Get(rowkey.getBytes());
Result rs = table.get(get);
for (KeyValue kv : rs.raw()) {
holdvalue = new String(kv.getValue());
}
I want to add columnfamily as a filter to access specific records that belongs to that specific rowKey and columnFamily. How could I achieve this?
Thanks in advance

You can add the column family as a filter by using the addFamily method of the Get object.
HTable table = new HTable(conf, "tablename");
Get get = new Get(rowkey.getBytes());
get.addFamily(family.getBytes()); // <-----------------
Result rs = table.get(get);
for (KeyValue kv : rs.raw()) {
holdvalue = new String(kv.getValue());
}

Related

Retrieve selected data from DynamoDB local in java

I have created a table in my local dynamoDB. The fields are,
id (N)
name (S)
school (S)
classname (S)
Now I want to retrieve all the records for which school equals to "xschool" and print.
Tried the below code but it gives me an error in the query,
QuerySpec spec = new QuerySpec().withProjectionExpression("sid, classname, school")
.withKeyConditionExpression("school = :v_school").
withValueMap(new ValueMap().withString(":v_school", "abcschool"));
ItemCollection<QueryOutcome> items = table.query(spec);
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
Any suggestions for this as I'm new to dynamoDB.
AmazonDynamoDB dynamoDBClient = createClient();
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
String tableName = "student";
Table table = dynamoDB.getTable(tableName);
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":sc", schoolname);
ItemCollection<ScanOutcome> items = table.scan("school = :sc", // FilterExpression
"sid, school, firstname, classname", // ProjectionExpression
null, // ExpressionAttributeNames - not used in this example
expressionAttributeValues);
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
Try this, I think this will work for you
From the DynamoDB documentation:
The Query operation enables you to query a table or a secondary index. You must provide a partition key value and an equality condition.
The error message you got means that school is not the partition key of your table. To fix this you can
change the table definition so that school is the partition key or
use a scan instead of a query.

Delete specific rows from an Access table using Jackcess

I am using the Jackcess API with an Access database. I open the database and get a specific table. How can I get the data (rows) from this table which matches a list of ids?
For example get all the rows from the table where id is in List.
private List<Component> disabledComponentsIds;
private Database db = null;
db = Database.open(new File(target), false, false);
Table table = db.getTable("t_object");
Table packages = db.getTable("t_package");
for(Map<String, Object> r : table){
if(disabledComponentsIds.contains(r.get("ea_guid"))){
r.get("package_id");
//Delete row from t_package table where id = r.get("package_id")
}
}
In this particular case I want to delete the rows.
Given a table named "t_object" ...
object_id object_name
--------- -----------
1 alpha
2 bravo
3 charlie
4 delta
5 echo
... where "object_id" is the primary key, you could delete specific rows like so:
// test data
ArrayList<Integer> enabledComponentsIds = new ArrayList<>();
enabledComponentsIds.add(2);
enabledComponentsIds.add(3);
String dbFileSpec = "C:/Users/Public/jackcessTest.mdb";
try (Database db = DatabaseBuilder.open(new File(dbFileSpec))) {
Table t = db.getTable("t_object");
for (int id : enabledComponentsIds) {
Row r = CursorBuilder.findRowByPrimaryKey(t, id);
if (r != null) {
t.deleteRow(r);
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
That will delete the rows where "object_id" is 2 or 3.
Edit:
If the column is not indexed then you'll have to iterate through each row (as Kayaman suggested) and see if its column value is contained in the list:
// test data
ArrayList<Integer> enabledComponentsIds = new ArrayList<>();
enabledComponentsIds.add(2);
enabledComponentsIds.add(3);
String dbFileSpec = "C:/Users/Public/jackcessTest.mdb";
try (Database db = DatabaseBuilder.open(new File(dbFileSpec))) {
Table t = db.getTable("t_object");
for (Row r : t) {
if (enabledComponentsIds.contains(r.getInt("object_id"))) {
t.deleteRow(r);
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
Jackcess provides very limited functionality for querying the data, so your best option is to go through the table with an iterator (or streams).
for(Row r : myTable)
; // perform any filtering based on rows here

Java - Set generic table with SQL results

Below you can find the code that I'm using to retrieve a table from a generic SQL statement (the SQL code is inputed by the user in another part of the code).
Since I'll be storing more than one table in the future, and the retrieved table will have some format functions applied to it, I'm storing the values in a:
Map<String, Map<String,List<Object>>> tables = new HashMap<String, Map<String,List<Object>>>();
The first Map is a Table, the second is a Column and finally the list hold each line of data.
The column names/order in:
Map<String, TreeMap<Integer, String>> order = new HashMap<String, TreeMap<Integer, String>>();
The Map is tha table, the TreeMap are the column number - column name
The code to create de generic table is:
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
for(int i = 1; i <= rsmd.getColumnCount(); i++){
String name = rsmd.getColumnLabel(i); //Label vs name. Label is also what's defined by the user in: "as VENDA"
answer.put(name, null);
singleOrder.put(i, name);
}
while(rs.next()){
Iterator answerIt = answer.entrySet().iterator();
while (answerIt.hasNext()) { //Get Columns in index order to compare with body HashMap (unordered)
Map.Entry columnNameValue = (Map.Entry)answerIt.next(); //key = columnName, value = List
String columnName = (String) columnNameValue.getKey();
List<Object> tmp = answer.get(columnName);
if (tmp == null) {
tmp = new ArrayList<Object>();
answer.put(columnName, tmp);
}
Object item = rs.getObject(columnName);
if(item instanceof Integer){
item = ((Integer) item).doubleValue();
} else if (item instanceof Long){
item = ((Long) item).doubleValue();
} else if (item instanceof BigDecimal){
item = ((BigDecimal) item).doubleValue();
}
tmp.add(item);
}
}
Efficiency will be key for this part of my code. How can I improve the table creation?
(I think this is a important question for Java coders, so a clear response can serve a pattern for future programmers that have the same difficulty that I'm having now)
Update 1:
Why I'm asking: I couldn't find any example of how to handle a flexible query in Java. I've created my own solution, but I fear it's some kind of monster compared to how to handle such a case properly in Java.
As example:
Lets say I'll name the result of a first query as "table1".
The query will be: Select STORE, SALES, GOAL, EXTRA from ... ;
The order variable will be like:
Map<String, TreeMap<Integer, String>> order = new HashMap<String, TreeMap<Integer, String>>();
table1,
1, "STORE"
2, "SALES"
3, "GOAL"
4, "EXTRA"
The tables variable:
Map<String, Map<String,List<Object>>> tables = new HashMap<String, Map<String,List<Object>>>();
"table1",
"STORE",
"unit1"
"unit2"
"unit3"
"unit4"
"SALES",
1312
126
1361
6823
"GOAL"
1300
160
1200
6000
"EXTRA"
"info1"
"info2"
"info3"
"info4"

send a query in neo4j [JAVA]

I am new to neo4j and graph database, and I have to send a query to get some values.
I have food and category nodes, and the relationship type between the two is specified by another node categorized_as.
What I need to fetch is the pair of food_name and its category_name.
Thanks for your help in advance.
Here's the documentation on how to run cypher queries from java. Adapted for your example, it would look like this:
// Create a new graph DB at path DB_PATH
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
// Create a new execution engine for running queries.
ExecutionEngine engine = new ExecutionEngine( db );
ExecutionResult result;
// Queries need to be run inside of transactions...
try ( Transaction ignored = db.beginTx() )
{
String query = "MATCH (f:food)-[:categorized_as]->(c:category) RETURN f.food_name as foodName, c.category_name as categoryName";
// Run that query we just defined.
result = engine.execute(query);
// Pull out the "foodNames" column from the result indicated by the query.
Iterator<String> foodNames = result.columnAs( "foodName" );
// Iterate through foodNames...
}

Get RowId from QueryChangeDescription

To my Oracle Database I have registered a DatabaseChangeNotification with a SQL-Query. I like to get any changes on the defined TABLE.
DatabaseChangeRegistration changeRegistration;
Properties properties = new Properties();
properties.setProperty(OracleConnection.DCN_NOTIFY_ROWIDS, "true");
properties.setProperty(OracleConnection.DCN_QUERY_CHANGE_NOTIFICATION, "true")
changeRegistration = connection.registerDatabaseChangeNotification(properties);
DCNListener dcnListener = new DCNListener(this);
changeRegistration.addListener(this);
Statement statement = connection.createStatement();
((OracleStatement) statement).setDatabaseChangeRegistration(changeRegistration);
String sql = "SELECT * from TABLE";
statement.executeQuery(sql);
In my Listener I receive the DatabaseChangeEvents
public void onDatabaseChangeNotification(DatabaseChangeEvent databaseChangeEvent) {
TableChangeDescription[] tableChangeDescription = databaseChangeEvent.getTableChangeDescription();
QueryChangeDescription[] queryChangeDescription = databaseChangeEvent.getQueryChangeDescription();
for (QueryChangeDescription qcd: queryChangeDescription) {
String result = qcd.toString();
System.out.println(qcd);
}
}
tabelChangeDescription is null
My result is:
query ID=201, query change event type=QUERYCHANGE
Table Change Description (length=1): operation=[UPDATE], tableName=USER.TABLE, objectNumber=67385
Row Change Description (length=1):
ROW: operation=UPDATE, ROWID=AAAQc5AAHAAAAG/AAB
Is there any nice way to get the ROWID from the Changes row else than String-Parsing? I can't find any getRowId-Method on the QueryChangeDescription.
I found the was to get the RowId. From the queryChangeDescription you can get the TabeleChangeDesciptions which has nothing in Common with the TableChangeDecription from the event. If there are changes on more than one Table, these tables where listed in the Array.
Because I am registered to only one Table I don't have to iterate over the list.
After habing the the TableChangeDescriptionyou can get the RowChangeDescription for each changed row. From this you can get the RowId.
for (QueryChangeDescription queryChangeDescription : databaseChangeEvent.getQueryChangeDescription()) {
RowChangeDescription[] rowChangeDescriptions = queryChangeDescription.getTableChangeDescription()[0].getRowChangeDescription();
for (RowChangeDescription rowChangeDescription : rowChangeDescriptions) {
handleEvent(rowChangeDescription.getRowid());
}
}

Categories

Resources