Spark SQL + XML – How to escape column names with hyphen symbol

Assume that you have the below XML content

<?xml version="1.0" encoding="UTF-8"?>

You want to write a spark SQL program to parse this content and run queries against it. We can query all the data but if you want to run a query with where clause against the columns first-name, last-name and middle-name,the query wont work as those columns contains hypen in it.

Now you have two solutions.
Either you have to get rid of hypen symbol by replacing it(Please refer my another post to know how to do this Spark XML – How to replace hyphen symbols found in XML elements) with underscore/empty or use the back tick symbol. I have used the second solution. Please refer my below code

import org.apache.spark.sql.SQLContext
import org.apache.spark.{SparkConf, SparkContext}

object SparkUserDataOperation {

  def main(args: Array[String]) {
    if (args.length < 1) {
      println("Usage ")
    val inFile = args(0)
    val conf = new SparkConf().setAppName("SparkUserDataOperation")
    val sc = new SparkContext(conf)
    //Create the SQL context
    val sqlContext = new SQLContext(sc)
    val df =
      .option("rootTag", "users")
      .option("rowTag", "user")

    //Map it to a table
    //Query it
    val allResults = sqlContext.sql("SELECT * FROM users").collect()
    print("Print all records::")
     //Note that the first-name is surrounded with backtick symbol.
    val specificResults = sqlContext.sql("SELECT * FROM users where `first-name` IN ('Bala')").collect()
    print("Print Query records::")