passing values using hivevar in HIVE - hive

I've got a param which is like "This is a param", and I'm going to pass it to below hiveQL:
hive -hivevar sys_nm="This is a param" -e 'select * from rd_sys where rd_sys_nm=${hivevar:sys_nm}'
But Hive returned below error message:
Logging initialized using configuration in jar:file:/opt/mapr/hive/hive-0.13/lib/hive-common-0.13.0-mapr-1409.jar!/hive-log4j.properties
FAILED: ParseException line 1:49 missing EOF at 'is' near 'This'
g4t7491_[mgr#g4t7491 ~]$
Does anyone know how to pass it normally?

Hive var don't work like hiveconf where you need to apply "hiveconf:somthing" in the code
when declaring hivevar just add the var name like this -> ${var_name}
for example:
through command line:
hive -hivevar MONTH_VAR='11' -e "select * from table where month=${MONTH_VAR};"
you can also declair through the script:
set hivevar:MONTH_VAR=11;
-- so query would look like this (no hiveconf):
set hivevar:MONTH_VAR=11;
SELECT * from table where month=${MONTH_VAR};

You need to put the string in single quotes for it to parse correctly as a string inside the sql after interpolation.
hive -hivevar sys_nm="'This is a param'" -e 'select * from rd_sys where rd_sys_nm=${hivevar:sys_nm}'

Related

How to declare and use variable in Hive SQL?

I am using below syntax to declare and use variable in hive sql query. But it gives me an error as below
SET aa='10';
SELECT
col1 as data,
${aa} as myVar from myTable;
ERROR:
org.apache.hive.service.cli.HiveSQLException: Error while processing statement: Cannot modify aa at runtime. It is not in list of params that are allowed to be modified at runtime
I have also tried using hiveconf
SELECT ${hiveconf:aa} from myTable;
You can not pass variable like that. You need to use --hivevar. You can create a hql file with below script - hiveqry.hql. Pls note you can use either a normal variable or with hivevar keyword.
select * from ${hivevar:aa};
select * from ${aa};
Then call that script like below
beeline --hivevar table=myTable --hivevar aa=100 -f hiveqry.hql
Depending on Hive version, when you are setting variable without explicitly specifying the namespace (hiveconf or hivevar), it may work with hiveconf as a default namespace or may not work.
BTW this works in Hive 1.2:
SET aa='10';
SELECT ${hiveconf:aa};
If you specify the namespace explicitly when setting variable, it will work with both hivevar and hiveconf
Works:
SET hivevar:aa='10';
SELECT ${hivevar:aa};
Also works:
SET hiveconf:aa='10';
SELECT ${hiveconf:aa};
Does not work:
SET aa='10';
SELECT ${hivevar:aa} as myvar;
Also if above commands do not work, check if variable substitution is enabled (default is true):
set hive.variable.substitute=true;
If set to false, substitution does not work.
Read the documentation: LanguageManual VariableSubstitution

How can we replace value of hive variables to check for any errors

We have a query in which we have defined more than 50 variables.
we call this hql via shell script, most of the times i get into syntax issue where i have not defined hive variables properly in the query.
Example
set hive var0=value0;
set hive var1=value1;
set hive var2=value2;
select * from ${hiveconf:var0} where col1=${hiveconf:var1} and col2=${hiveconf:var2};
I want to to check the above query result after replacing hive variables,
So is there a way to check if the variables are parsed in the right way or are there any syntax errors.
Please let me know for any alternatives as well.
Better use hivevar namespace for the same.
You can print all variable using ! echo command:
set hivevar:var0=value0;
hive> ! echo Variable hivevar:var0 is ${hivevar:var0};
Result:
Variable hivevar:var0 is value0
Also use explain extended <query> - it will print detailed query plan with predicates and fail if it is syntax error.
Update:
Also you can use SELECT for doing the same and Hive can execute simple queries without MR started if hive.fetch.task.conversion is set to more or minimal. If you are using Qubole, add also limit 1 to the query:
set hive.fetch.task.conversion=more;
select 'Variable hivevar:var0 is', '${hivevar:var0}' limit 1;
Why you may need to do this using SELECT? For example for easy checking parameter using casting or some UDF. If you need to check if parameter is of type DATE, use
set hive.fetch.task.conversion=more;
select 'Variable hivevar:var0 is', date '${hivevar:var0}' limit 1;
In this case if ${hivevar:var0} is not date, then type cast exception will be thrown and script execution terminated.
along with hivevar namespace, we can use one more property hive.root.logger=INFO,console.
this will display the query after replacing the variable value, from which we can find out the issue.
cat test.hql
set hivevar:var1=${hivevar:var11};
set hivevar:var2=2345;
select ${hivevar:var11};
select ${hivevar:var2};
hive command - hive --hiveconf hive.root.logger=INFO,console --hivevar var11=1234 -f test.hql
output on console
select 1234
2018-10-17T08:23:31,632 INFO [main] ql.Driver: Completed executing command(queryId=-4dd6-493f-88be-03810f847fe7); Time taken: 0.003 seconds
OK
2018-10-17T08:23:31,632 INFO [main] ql.Driver: OK
2018-10-17T08:23:31,670 INFO [main] io.NullRowsInputFormat$NullRowsRecordReader: Using null rows input format
1234

beeline spool Hive puts special character instead of quote

I am exporting query results form hive using beeline, here is my command :
beeline -u 'jdbc:hive2://myhost.com:10000/mydb;principal=hive/myhost.COM' --incremental=true --silent=true --outputformat=dsv --disableQuotingForSV=true --delimiterForDSV=\, --showHeader=false --nullemptystring=true -f myquery.hql --hiveconf DT_ID=${DT_ID} > ${spoolFile}
This is my query :
SELECT id, concat('"',c_name,'"'), app_name from mytab where dt_id='${hiveconf:DT_ID}';
But I get results like this, for fields having my field separator(,) in column value:
66,**^#**"(Chat\, Social\, Music\, Utilities)"**^#**,Default
Note the ^#. Why is it coming? How can avoid it? What is that character? If it is quote, I am to have it, so that I can remove the concat in my query. I tried playing with --disableQuotingForSV=true/false. But that did not help me.

Hive coalesce parse exception

I want to create a hive script that uses as database one of two given parameters, whichever is not null.
My hive-test.sql is this:
set db_name = coalesce(${hiveconf:dbOne}, ${hiveconf:dbTwo});
use ${hiveconf:db_name};
show tables;
and I run it with:
hive -hiveconf dbOne=my_database -f hive-test.sql
and I am getting:
FAILED: ParseException line 2:12 missing EOF at '(' near 'coalesce'
I should note that if I change the first line in script to:
set db_name = my_database;
it works.
I can't figure out what I did wrong. Your assistance is appreciated.
This feature is not available in Hive.
Do variable assignment in the shell, for example like here: setting-a-shell-variable-in-a-null-coalescing-fashion and pass it to the Hive.

How to set variables in HIVE scripts

I'm looking for the SQL equivalent of SET varname = value in Hive QL
I know I can do something like this:
SET CURRENT_DATE = '2012-09-16';
SELECT * FROM foo WHERE day >= #CURRENT_DATE
But then I get this error:
character '#' not supported here
You need to use the special hiveconf for variable substitution.
e.g.
hive> set CURRENT_DATE='2012-09-16';
hive> select * from foo where day >= ${hiveconf:CURRENT_DATE}
similarly, you could pass on command line:
% hive -hiveconf CURRENT_DATE='2012-09-16' -f test.hql
Note that there are env and system variables as well, so you can reference ${env:USER} for example.
To see all the available variables, from the command line, run
% hive -e 'set;'
or from the hive prompt, run
hive> set;
Update:
I've started to use hivevar variables as well, putting them into hql snippets I can include from hive CLI using the source command (or pass as -i option from command line).
The benefit here is that the variable can then be used with or without the hivevar prefix, and allow something akin to global vs local use.
So, assume have some setup.hql which sets a tablename variable:
set hivevar:tablename=mytable;
then, I can bring into hive:
hive> source /path/to/setup.hql;
and use in query:
hive> select * from ${tablename}
or
hive> select * from ${hivevar:tablename}
I could also set a "local" tablename, which would affect the use of ${tablename}, but not ${hivevar:tablename}
hive> set tablename=newtable;
hive> select * from ${tablename} -- uses 'newtable'
vs
hive> select * from ${hivevar:tablename} -- still uses the original 'mytable'
Probably doesn't mean too much from the CLI, but can have hql in a file that uses source, but set some of the variables "locally" to use in the rest of the script.
Most of the answers here have suggested to either use hiveconf or hivevar namespace to store the variable. And all those answers are right. However, there is one more namespace.
There are total three namespaces available for holding variables.
hiveconf - hive started with this, all the hive configuration is stored as part of this conf. Initially, variable substitution was not part of hive and when it got introduced, all the user-defined variables were stored as part of this as well. Which is definitely not a good idea. So two more namespaces were created.
hivevar: To store user variables
system: To store system variables.
And so if you are storing a variable as part of a query (i.e. date or product_number) you should use hivevar namespace and not hiveconf namespace.
And this is how it works.
hiveconf is still the default namespace, so if you don't provide any namespace it will store your variable in hiveconf namespace.
However, when it comes to referring a variable, it's not true. By default it refers to hivevar namespace. Confusing, right? It can become clearer with the following example.
If you do not provide namespace as mentioned below, variable var will be stored in hiveconf namespace.
set var="default_namespace";
So, to access this you need to specify hiveconf namespace
select ${hiveconf:var};
And if you do not provide namespace it will give you an error as mentioned below, reason being that by default if you try to access a variable it checks in hivevar namespace only. And in hivevar there is no variable named var
select ${var};
We have explicitly provided hivevar namespace
set hivevar:var="hivevar_namespace";
as we are providing the namespace this will work.
select ${hivevar:var};
And as default, workspace used during referring a variable is hivevar, the following will work too.
select ${var};
Have you tried using the dollar sign and brackets like this:
SELECT *
FROM foo
WHERE day >= '${CURRENT_DATE}';
Just in case someone needs to parameterize hive query via cli.
For eg:
hive_query.sql
SELECT * FROM foo WHERE day >= '${hivevar:CURRENT_DATE}'
Now execute above sql file from cli:
hive --hivevar CURRENT_DATE="2012-09-16" -f hive_query.sql
Two easy ways:
Using hive conf
hive> set USER_NAME='FOO';
hive> select * from foobar where NAME = '${hiveconf:USER_NAME}';
Using hive vars
On your CLI set vars and then use them in hive
set hivevar:USER_NAME='FOO';
hive> select * from foobar where NAME = '${USER_NAME}';
hive> select * from foobar where NAME = '${hivevar:USER_NAME}';
Documentation: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+VariableSubstitution
One thing to be mindful of is setting strings then referring back to them. You have to make sure the quotes aren't colliding.
set start_date = '2019-01-21';
select ${hiveconf:start_date};
When setting dates then referring to them in code as the strings can conflict. This wouldn't work with the start_date set above.
'${hiveconf:start_date}'
We have to be mindful of not setting twice single or double quotes for strings when referring back to them in the query.
There are multiple options to set variables in Hive.
If you're looking to set Hive variable from inside the Hive shell, you can set it using hivevar. You can set string or integer datatypes. There are no problems with them.
SET hivevar:which_date=20200808;
select ${which_date};
If you're planning to set variables from shell script and want to pass those variables into your Hive script (HQL) file, you can use --hivevar option while calling hive or beeline command.
# shell script will invoke script like this
beeline --hivevar tablename=testtable -f select.hql
-- select.hql file
select * from <dbname>.${tablename};
Try this method:
set t=20;
select *
from myTable
where age > '${hiveconf:t}';
it works well on my platform.
You can export the variable in shell script
export CURRENT_DATE="2012-09-16"
Then in hiveql you like
SELECT * FROM foo WHERE day >= '${env:CURRENT_DATE}'
You can store the output of another query in a variable and latter you can use the same in your code:
set var=select count(*) from My_table;
${hiveconf:var};