hive源码之get_json_object

这篇具有很好参考价值的文章主要介绍了hive源码之get_json_object。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

一、get_json_object 使用

二、使用案例

三、源码分析

四、总结


大家好,我是老六。

在数据开发中,我们有大量解析json串的需求,我们选用的UDF函数无非就是:get_json_object和json_tuple。但是在使用get_json_object函数过程中,老六发现get_json_object无法解析key为中文的key:value对。带着这个问题,老六通过源码研究了get_json_object这个函数,探索其中奥秘。

一、get_json_object 使用

  • 语法:get_json_object(json_string, '$.key')
  • 说明:解析json的字符串json_string,返回path指定的内容。如果输入的json字符串无效,那么返回NULL。这个函数每次只能返回一个数据项。

二、使用案例

本案例是在hive1.2.1版本下实测,可供参考,若有出入,请对照相应版本源码。

构造JSON串:{"gg今日":"gg今日","test":"test","gg":"gg","今日":"今日"}

hive get_json_object,Hive源码,json,hive,sql,mapreduce,java

1、正常案例

SQL:select get_json_object('{"gg今日":"gg今日","test":"test","gg":"gg","今日":"今日"}',"$.test");

结果:

hive get_json_object,Hive源码,json,hive,sql,mapreduce,java

 结果很正常,就是解析json,通过key来取value

2、异常案例

1)SQL:select get_json_object('{"gg今日":"gg今日","test":"test","gg":"gg","今日":"今日"}',"$.今日");

结果:

hive get_json_object,Hive源码,json,hive,sql,mapreduce,java

 结果开始有些不对了,按照函数使用来说,我理解是可以正常取到 今日:今日键值对,但是结果是null,开始好奇,想搞明白原因是什么。

再次测试

2)SQL:select get_json_object('{"gg今日":"gg今日","test":"test","gg":"gg","今日":"今日"}',"$.gg今日");

结果:

hive get_json_object,Hive源码,json,hive,sql,mapreduce,java

这就很神奇了, 以 'gg今日' 作为键却取出了以'gg'作为键的结果,缘分真是妙不可言呐。

通过测试我们发现两个问题:

1)中文作为key,get_json_object无法取出value值(见 2.1)。

2)以英文开头的混有中文的key,取出了英文部分key对应的value(见 2.2)。

三、源码分析

通过查看源码我们发现get_json_object对应的UDF类的源码如下:

/**
 * UDFJson.
 *
 */
@Description(name = "get_json_object",
    value = "_FUNC_(json_txt, path) - Extract a json object from path ",
    extended = "Extract json object from a json string based on json path "
    + "specified, and return json string of the extracted json object. It "
    + "will return null if the input json string is invalid.\n"
    + "A limited version of JSONPath supported:\n"
    + "  $   : Root object\n"
    + "  .   : Child operator\n"
    + "  []  : Subscript operator for array\n"
    + "  *   : Wildcard for []\n"
    + "Syntax not supported that's worth noticing:\n"
    + "  ''  : Zero length string as key\n"
    + "  ..  : Recursive descent\n"
    + "  @   : Current object/element\n"
    + "  ()  : Script expression\n"
    + "  ?() : Filter (script) expression.\n"
    + "  [,] : Union operator\n"
    + "  [start:end:step] : array slice operator\n")
public class UDFJson extends UDF {
  private final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s]+).*");
  private final Pattern patternIndex = Pattern.compile("\\[([0-9]+|\\*)\\]");

  private static final JsonFactory JSON_FACTORY = new JsonFactory();
  static {
    // Allows for unescaped ASCII control characters in JSON values
    JSON_FACTORY.enable(Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
  }
  private static final ObjectMapper MAPPER = new ObjectMapper(JSON_FACTORY);
  private static final JavaType MAP_TYPE = TypeFactory.fromClass(Map.class);
  private static final JavaType LIST_TYPE = TypeFactory.fromClass(List.class);

  // An LRU cache using a linked hash map
  static class HashCache<K, V> extends LinkedHashMap<K, V> {

    private static final int CACHE_SIZE = 16;
    private static final int INIT_SIZE = 32;
    private static final float LOAD_FACTOR = 0.6f;

    HashCache() {
      super(INIT_SIZE, LOAD_FACTOR);
    }

    private static final long serialVersionUID = 1;

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
      return size() > CACHE_SIZE;
    }

  }

  static Map<String, Object> extractObjectCache = new HashCache<String, Object>();
  static Map<String, String[]> pathExprCache = new HashCache<String, String[]>();
  static Map<String, ArrayList<String>> indexListCache =
      new HashCache<String, ArrayList<String>>();
  static Map<String, String> mKeyGroup1Cache = new HashCache<String, String>();
  static Map<String, Boolean> mKeyMatchesCache = new HashCache<String, Boolean>();

  Text result = new Text();

  public UDFJson() {
  }

  /**
   * Extract json object from a json string based on json path specified, and
   * return json string of the extracted json object. It will return null if the
   * input json string is invalid.
   *
   * A limited version of JSONPath supported: $ : Root object . : Child operator
   * [] : Subscript operator for array * : Wildcard for []
   *
   * Syntax not supported that's worth noticing: '' : Zero length string as key
   * .. : Recursive descent &amp;#064; : Current object/element () : Script
   * expression ?() : Filter (script) expression. [,] : Union operator
   * [start:end:step] : array slice operator
   *
   * @param jsonString
   *          the json string.
   * @param pathString
   *          the json path expression.
   * @return json string or null when an error happens.
   */
  public Text evaluate(String jsonString, String pathString) {

    if (jsonString == null || jsonString.isEmpty() || pathString == null
        || pathString.isEmpty() || pathString.charAt(0) != '$') {
      return null;
    }

    int pathExprStart = 1;
    boolean isRootArray = false;

    if (pathString.length() > 1) {
      if (pathString.charAt(1) == '[') {
        pathExprStart = 0;
        isRootArray = true;
      } else if (pathString.charAt(1) == '.') {
        isRootArray = pathString.length() > 2 && pathString.charAt(2) == '[';
      } else {
        return null;
      }
    }

    // Cache pathExpr
    String[] pathExpr = pathExprCache.get(pathString);
    if (pathExpr == null) {
      pathExpr = pathString.split("\\.", -1);
      pathExprCache.put(pathString, pathExpr);
    }

    // Cache extractObject
    Object extractObject = extractObjectCache.get(jsonString);
    if (extractObject == null) {
      JavaType javaType = isRootArray ? LIST_TYPE : MAP_TYPE;
      try {
        extractObject = MAPPER.readValue(jsonString, javaType);
      } catch (Exception e) {
        return null;
      }
      extractObjectCache.put(jsonString, extractObject);
    }
    for (int i = pathExprStart; i < pathExpr.length; i++) {
      if (extractObject == null) {
          return null;
      }
      extractObject = extract(extractObject, pathExpr[i], i == pathExprStart && isRootArray);
    }
    if (extractObject instanceof Map || extractObject instanceof List) {
      try {
        result.set(MAPPER.writeValueAsString(extractObject));
      } catch (Exception e) {
        return null;
      }
    } else if (extractObject != null) {
      result.set(extractObject.toString());
    } else {
      return null;
    }
    return result;
  }

  private Object extract(Object json, String path, boolean skipMapProc) {
    // skip MAP processing for the first path element if root is array
    if (!skipMapProc) {
      // Cache patternkey.matcher(path).matches()
      Matcher mKey = null;
      Boolean mKeyMatches = mKeyMatchesCache.get(path);
      if (mKeyMatches == null) {
        mKey = patternKey.matcher(path);
        mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
        mKeyMatchesCache.put(path, mKeyMatches);
      }
      if (!mKeyMatches.booleanValue()) {
        return null;
      }

      // Cache mkey.group(1)
      String mKeyGroup1 = mKeyGroup1Cache.get(path);
      if (mKeyGroup1 == null) {
        if (mKey == null) {
          mKey = patternKey.matcher(path);
          mKeyMatches = mKey.matches() ? Boolean.TRUE : Boolean.FALSE;
          mKeyMatchesCache.put(path, mKeyMatches);
          if (!mKeyMatches.booleanValue()) {
            return null;
          }
        }
        mKeyGroup1 = mKey.group(1);
        mKeyGroup1Cache.put(path, mKeyGroup1);
      }
      json = extract_json_withkey(json, mKeyGroup1);
    }
    // Cache indexList
    ArrayList<String> indexList = indexListCache.get(path);
    if (indexList == null) {
      Matcher mIndex = patternIndex.matcher(path);
      indexList = new ArrayList<String>();
      while (mIndex.find()) {
        indexList.add(mIndex.group(1));
      }
      indexListCache.put(path, indexList);
    }

    if (indexList.size() > 0) {
      json = extract_json_withindex(json, indexList);
    }

    return json;
  }

  private transient AddingList jsonList = new AddingList();

  private static class AddingList extends ArrayList<Object> {
    @Override
    public Iterator<Object> iterator() {
      return Iterators.forArray(toArray());
    }
    @Override
    public void removeRange(int fromIndex, int toIndex) {
      super.removeRange(fromIndex, toIndex);
    }
  };

  @SuppressWarnings("unchecked")
  private Object extract_json_withindex(Object json, ArrayList<String> indexList) {

    jsonList.clear();
    jsonList.add(json);
    for (String index : indexList) {
      int targets = jsonList.size();
      if (index.equalsIgnoreCase("*")) {
        for (Object array : jsonList) {
          if (array instanceof List) {
            for (int j = 0; j < ((List<Object>)array).size(); j++) {
              jsonList.add(((List<Object>)array).get(j));
            }
          }
        }
      } else {
        for (Object array : jsonList) {
          int indexValue = Integer.parseInt(index);
          if (!(array instanceof List)) {
            continue;
          }
          List<Object> list = (List<Object>) array;
          if (indexValue >= list.size()) {
            continue;
          }
          jsonList.add(list.get(indexValue));
        }
      }
      if (jsonList.size() == targets) {
        return null;
      }
      jsonList.removeRange(0, targets);
    }
    if (jsonList.isEmpty()) {
      return null;
    }
    return (jsonList.size() > 1) ? new ArrayList<Object>(jsonList) : jsonList.get(0);
  }

  @SuppressWarnings("unchecked")
  private Object extract_json_withkey(Object json, String path) {
    if (json instanceof List) {
      List<Object> jsonArray = new ArrayList<Object>();
      for (int i = 0; i < ((List<Object>) json).size(); i++) {
        Object json_elem = ((List<Object>) json).get(i);
        Object json_obj = null;
        if (json_elem instanceof Map) {
          json_obj = ((Map<String, Object>) json_elem).get(path);
        } else {
          continue;
        }
        if (json_obj instanceof List) {
          for (int j = 0; j < ((List<Object>) json_obj).size(); j++) {
            jsonArray.add(((List<Object>) json_obj).get(j));
          }
        } else if (json_obj != null) {
          jsonArray.add(json_obj);
        }
      }
      return (jsonArray.size() == 0) ? null : jsonArray;
    } else if (json instanceof Map) {
      return ((Map<String, Object>) json).get(path);
    } else {
      return null;
    }
  }
}
private final Pattern patternKey = Pattern.compile("^([a-zA-Z0-9_\\-\\:\\s]+).*"); 这个就是匹配key的模式串,它的意思是匹配以数字、字母、_、-、:、空格 为开头的字符串。那么这个匹配模式串就决定了,get_json_object函数无法匹配出key是纯中文的键值对,即select get_json_object('{"gg今日":"gg今日","test":"test","gg":"gg","今日":"今日"}',"$.今日") 结果为null;
对于 select get_json_object('{"gg今日":"gg今日","test":"test","gg":"gg","今日":"今日"}',"$.gg今日"),由于匹配key的模式串是匹配以数字、字母、_、-、:、空格 为开头的字符串,所以它将'gg今日'中的'gg'匹配出来,然后作为key去取value,所以就取出了 "gg":"gg" 键值对,即答案为'gg'。

四、总结

实践是检验真理的唯一标准。遇到问题,我们就去它的源头寻找答案。


hive get_json_object,Hive源码,json,hive,sql,mapreduce,java

欢迎关注微信公众号文章来源地址https://www.toymoban.com/news/detail-780490.html

到了这里,关于hive源码之get_json_object的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • flink1.17 实现 udf scalarFunctoin get_json_object 支持 非标准化json

    相比官方的json_value,该函数支持非标准化json,比如v是个object,但是非标准json会外套一层引号,内部有反引号. eg:  {\\\"kkkk2\\\":  \\\"{\\\"kkkk1\\\":\\\"vvvvvvv\\\"}\\\" } 支持value为 100L 这种java格式的bigint.    {\\\"k\\\":999L} 基于jsonPath 方便,可以获取多层级内部值

    2024年02月11日
    浏览(28)
  • get属性是什么?有什么用?在什么场景用?get会被Json序列化?

    在JavaScript中,对象的属性不仅可以是数据属性(即常规的键值对),还可以是访问器属性(accessor properties)。访问器属性不包含实际的数据值,而是定义了如何获取(get)和设置(set)一个值。这些操作由getter和setter函数执行。 get 属性(getter) get 是一种定义在对象内部的

    2024年02月11日
    浏览(26)
  • 前端 axios 通过 get 请求发送 json 数据

    先说结论: axios 不能通过 get 请求发送 json 数据 使用 postman 可以做到通过 get 请求发送 json 数据 但是通过 axios 框架就不行, 主要是因为axios是对ajax的一个封装。他本身不支持get请求在body体传参。 原生和jquery的ajax是支持的。建议跟后端沟通,你把json拼在url后面,后端从url的

    2024年02月11日
    浏览(46)
  • 【Jmeter之get请求传递的值为JSON体实践】

    Jmeter之get请求传递的值为JSON体实践 1、在URL地址后面拼接,有多个key和value时,用链接 2、在Parameters里面加上key和value 尝试一:把json放到value,勾选编码,发送请求后报错,提示参数异常 尝试二:把json进行URL编码后,再放到URL地址后面,发现json里面有需要参数化的值,所以

    2024年01月16日
    浏览(27)
  • java http get post 和 发送json数据请求

    浏览器请求效果       main调用  

    2024年02月16日
    浏览(38)
  • HIVE获取json字段特定值(单个json或者json数组)

    1.获取单个json字符串里的某一特定值 函数:get_json_object(单个json,‘$.要获取的字段’) 示例: 代码:SELECT get_json_object(‘{“NAME”:“张三”,“ID”:“1”}’,‘$.NAME’) as name; SELECT get_json_object(‘{“NAME”:“张三”,“ID”:“1”}’,‘$.NAME’); 2. json_tuple 语法:json_tuple(json_string,

    2024年02月08日
    浏览(31)
  • 7. Hive解析JSON字符串、JSON数组

    Hive解析JSON字符串 1. get_json_object 语法: get_json_object(json_string, path) json_string 是要解析的JSON字符串 path 是用于指定要提取的字段路径的字符串 局限性 get_json_object 函数的性能会受到 JSON数据的结构和大小 的影响。对于较复杂的嵌套结构,考虑使用Hive的其他函数或自定义函数来

    2024年02月11日
    浏览(39)
  • Hive初始化问题 Failed to get schema version.

    Hive初始化问题 Failed to get schema version. 引起Failed to get schema version.的原因有很多,我遇到的如下: 1.Public Key Retrieval is not allowed 原因分析: 如果用户使用了 sha256_password 认证,密码在传输过程中必须使用 TLS 协议保护,但是如果 RSA 公钥不可用,可以使用服务器提供的公钥;可

    2024年02月11日
    浏览(40)
  • hive解析json

    目录 一、背景 二、hive 解析 json 数据函数 1、get_json_object  2、json_tuple 3、使用嵌套子查询(explode+regexp_replace+split+json_tuple)解析json数组 4、使用 lateral view 解析json数组 5、解析非固定名称json 我们进行ETL(Extract-Transfer-Load)  过程中,经常会遇到从不同数据源获取的不同格式的数据,

    2024年02月09日
    浏览(25)
  • Hive解析JSON串

    Hive 处理 json 数据总体来说有两个方向的路走: 将 json 以字符串的方式整个入 Hive 表,然后通过使用 UDF 函数解析已经导入到 hive 中的数据,比如使用 LATERAL VIEW json_tuple 的方法,获取所需要的列名。 在导入之前将 json 拆成各个字段,导入 Hive 表的数据是已经解析过的。这将需

    2024年02月16日
    浏览(26)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包