반응형


MariaDB JSON 형식 데이터 사용 : MariaDB 10.2 부터 가능

참고 사이트

https://mariadb.com/kb/en/library/json-functions/
https://mariadb.com/resources/blog/json-with-mariadb-10-2/
https://bstar36.tistory.com/359


1. 버전 확인
    MariaDB [(test)]> select @@version;
    +-----------------+
    | @@version       |
    +-----------------+
    | 10.3.17-MariaDB |
    +-----------------+
    1 row in set (0.000 sec)

2. JSON 데이터 타입 지원(내부적으로 LongTEXT로 저장)    
    MariaDB [test]> create table json_test (id int, data json);
    Query OK, 0 rows affected (0.015 sec)

    MariaDB [test]> show create table json_test;
    +-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Table     | Create Table                                                                                                                                                                                  |
    +-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | json_test | CREATE TABLE `json_test` (
      `id` int(11) DEFAULT NULL,
      `data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
    +-----------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    1 row in set (0.000 sec)


3. JSON 데이터 조작
   A. json_object 함수를 이용하여 key,value 형식으로 Insert
    MariaDB [test]> insert into json_test values (1 , json_object('Name' , 'Kil-Dong, Hong' , 'Sex' , 'M' , 'Phone' , '010-1234-5678')) ;
    Query OK, 1 row affected (0.003 sec)
    
    MariaDB [test]> commit;
    Query OK, 0 rows affected (0.000 sec)
    
    MariaDB [test]> select * from json_test ;
    +------+------------------------------------------------------------------+
    | id   | data                                                             |
    +------+------------------------------------------------------------------+
    |    1 | {"Name": "Kil-Dong, Hong", "Sex": "M", "Phone": "010-1234-5678"} |
    +------+------------------------------------------------------------------+
    1 row in set (0.000 sec)

   B. 특정 key 값만 조회 하고자 할때 json_value 함수를 사용 
   
    MariaDB [test]> select id , json_value(data,'$.Name') As Name , json_value(data,'$.Phone') as Phone from json_test ;
    +------+----------------+---------------+
    | id   | Name           | Phone         |
    +------+----------------+---------------+
    |    1 | Kil-Dong, Hong | 010-1234-5678 |
    +------+----------------+---------------+
    1 row in set (0.001 sec)
    
    C. 특정 하나 Key 값을 update 하고자 할때,  json_replace 함수를 사용
    
    ※ 단, 이름은 중복날 수 있으니 Unique 값으로 비교하는 것을 추천 (사용방법 안내)
    MariaDB [test]> update json_test set data = json_replace(data,'$.Phone','010-2345-6789') where json_value(data,'$.Name') = 'Kil-Dong, Hong';
    Query OK, 1 row affected (0.002 sec)
    Rows matched: 1  Changed: 1  Warnings: 0


    MariaDB [test]> select id , json_value(data,'$.Name') As Name , json_value(data,'$.Phone') as Phone from json_test ;
    +------+----------------+---------------+
    | id   | Name           | Phone         |
    +------+----------------+---------------+
    |    1 | Kil-Dong, Hong | 010-2345-6789 |
    +------+----------------+---------------+
    1 row in set (0.000 sec)
    
    
    Object 값 자체로 추출("" 형태)
    MariaDB [test]> SELECT JSON_EXTRACT(data, '$.Name') from json_test;
    +------------------------------+
    | JSON_EXTRACT(data, '$.Name') |
    +------------------------------+
    | "Su, Peng"                   |
    | "Dori Go"                    |
    | "DaHan, Wi "                 |
    | NULL                         |
    | NULL                         |
    +------------------------------+
    5 rows in set (0.000 sec)
    
    
    MariaDB [test]> SELECT JSON_UNQUOTE(JSON_EXTRACT(data, '$.Name')) from json_test;
    +--------------------------------------------+
    | JSON_UNQUOTE(JSON_EXTRACT(data, '$.Name')) |
    +--------------------------------------------+
    | Su, Peng                                   |
    | Dori Go                                    |
    | DaHan, Wi                                  |
    | NULL                                       |
    | NULL                                       |
    +--------------------------------------------+
    5 rows in set (0.000 sec)


    
    D. 하나 이상의 Key 값을 변경할 때는 json_set 함수 사용

    MariaDB [test]> update json_test set data = json_set(data,'$.Phone','010-3456-7890', '$.Name','Su, Peng') where id = 1 ;
    Query OK, 1 row affected (0.001 sec)
    Rows matched: 1  Changed: 1  Warnings: 0

    MariaDB [test]> select id , json_value(data,'$.Name') As Name , json_value(data,'$.Phone') as Phone from json_test ;
    +------+----------+---------------+
    | id   | Name     | Phone         |
    +------+----------+---------------+
    |    1 | Su, Peng | 010-3456-7890 |
    +------+----------+---------------+
    1 row in set (0.000 sec)

 
    E. Json 형태가 추가되어도 입력이 가능
    insert into json_test values (2 , json_object('Name' , 'Dori Go' , 'Sex' , 'F' , 'Phone' , '02-123-4567' , 'Birth', '2000-01-01')) ; 
    
    MariaDB [test]> insert into json_test values (2 , json_object('Name' , 'Dori Go' , 'Sex' , 'F' , 'Phone' , '02-123-4567' , 'Birth', '2000-01-01')) ;
    Query OK, 1 row affected (0.001 sec)
    
    MariaDB [test]> commit;
    Query OK, 0 rows affected (0.000 sec)
    
    MariaDB [test]> select * from json_test;
    +------+--------------------------------------------------------------------------------+
    | id   | data                                                                           |
    +------+--------------------------------------------------------------------------------+
    |    1 | {"Name": "Su, Peng", "Sex": "M", "Phone": "010-3456-7890"}                     |
    |    2 | {"Name": "Dori Go", "Sex": "F", "Phone": "02-123-4567", "Birth": "2000-01-01"} |
    +------+--------------------------------------------------------------------------------+
    2 rows in set (0.000 sec)

    F. json 데이터 값의 Like 검색
    
    MariaDB [test]> select count(*) from json_test where json_value(data,'$.Phone') like '02%' ;
    +----------+
    | count(*) |
    +----------+
    |        1 |
    +----------+
    1 row in set (0.000 sec)
     
    G. json 데이터 타입의 key를 가상 컬럼을 생성 후 Index 작업 가능
    
    - 테이블 변경(가상 컬럼 추가)
    MariaDB [test]> alter table json_test add phone varchar(20) as (json_value(data,'$.phone')) ;
    Query OK, 0 rows affected (0.341 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    MariaDB [test]> select * from json_test limit 1 ;
    +------+------------------------------------------------------------+-------+
    | id   | data                                                       | phone |
    +------+------------------------------------------------------------+-------+
    |    1 | {"Name": "Su, Peng", "Sex": "M", "Phone": "010-3456-7890"} | NULL  |
    +------+------------------------------------------------------------+-------+
    1 row in set (0.000 sec)

    현재 화면에서 데이터가 안나오는 이유는 Key의 Phone은 P가 대문자 생성시에는 소문자로 만들었음
    삭제 후 다시 추가

    MariaDB [test]> alter table json_test drop phone;
    Query OK, 0 rows affected (0.009 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    MariaDB [test]>  select * from json_test limit 1 ;
    +------+------------------------------------------------------------+
    | id   | data                                                       |
    +------+------------------------------------------------------------+
    |    1 | {"Name": "Su, Peng", "Sex": "M", "Phone": "010-3456-7890"} |
    +------+------------------------------------------------------------+
    1 row in set (0.000 sec)

    MariaDB [test]> alter table json_test add phone varchar(20) as (json_value(data,'$.Phone')) ;
    Query OK, 0 rows affected (0.012 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    MariaDB [test]>  select * from json_test;
    +------+--------------------------------------------------------------------------------+---------------+
    | id   | data                                                                           | phone         |
    +------+--------------------------------------------------------------------------------+---------------+
    |    1 | {"Name": "Su, Peng", "Sex": "M", "Phone": "010-3456-7890"}                     | 010-3456-7890 |
    |    2 | {"Name": "Dori Go", "Sex": "F", "Phone": "02-123-4567", "Birth": "2000-01-01"} | 02-123-4567   |
    +------+--------------------------------------------------------------------------------+---------------+
    2 rows in set (0.000 sec)
    
       
    - 인덱스 생성
    key 값을 기준으로 가상 생성된 컬럼에 index를(ix_json_test_01)  추가
    MariaDB [test]> create index ix_json_test_01 on json_test(phone) ;
    Query OK, 0 rows affected (0.021 sec)
    Records: 0  Duplicates: 0  Warnings: 0
    
    explain 을 통해 plan을 조회합니다.
    MariaDB [test]> explain select count(*) from json_test where Phone like '02%' ;
    +------+-------------+-----------+-------+-----------------+-----------------+---------+------+------+--------------------------+
    | id   | select_type | table     | type  | possible_keys   | key             | key_len | ref  | rows | Extra                    |
    +------+-------------+-----------+-------+-----------------+-----------------+---------+------+------+--------------------------+
    |    1 | SIMPLE      | json_test | index | ix_json_test_01 | ix_json_test_01 | 63      | NULL |    2 | Using where; Using index |
    +------+-------------+-----------+-------+-----------------+-----------------+---------+------+------+--------------------------+
    1 row in set (0.000 sec)

    H. Json Object를 사용하지 않은 Insert
    MariaDB [test]> insert into json_test(id, data) values (3, '{"Name": "DaHan, Wi ", "Sex": "M", "Phone": "010-9876-5432", "Birth": "1999-12-31"}');
    Query OK, 1 row affected (0.003 sec)

    MariaDB [test]> select * from json_test;
    +------+-------------------------------------------------------------------------------------+---------------+
    | id   | data                                                                                | phone         |
    +------+-------------------------------------------------------------------------------------+---------------+
    |    1 | {"Name": "Su, Peng", "Sex": "M", "Phone": "010-3456-7890"}                          | 010-3456-7890 |
    |    2 | {"Name": "Dori Go", "Sex": "F", "Phone": "02-123-4567", "Birth": "2000-01-01"}      | 02-123-4567   |
    |    3 | {"Name": "DaHan, Wi ", "Sex": "M", "Phone": "010-9876-5432", "Birth": "1999-12-31"} | 010-9876-5432 |
    +------+-------------------------------------------------------------------------------------+---------------+
    3 rows in set (0.000 sec)


4. Json 관련 함수들
   관련 링크 :  https://mariadb.com/kb/en/library/json-functions/
   
   - JSON_Query와 JSON_VALUE 차이
     아래와 같이 임시로 json 변수를 선언하고 json 데이터를 저장합니다.
     
    MariaDB [test]> SET @json='{ "x": [0,1], "y": "[0,1]", "z": "Monty" }';
    Query OK, 0 rows affected (0.001 sec)

    MariaDB [test]> SELECT JSON_QUERY(@json,'$'), JSON_VALUE(@json,'$');
    +--------------------------------------------+-----------------------+
    | JSON_QUERY(@json,'$')                      | JSON_VALUE(@json,'$') |
    +--------------------------------------------+-----------------------+
    | { "x": [0,1], "y": "[0,1]", "z": "Monty" } | NULL                  |
    +--------------------------------------------+-----------------------+
    1 row in set (0.000 sec)

    MariaDB [test]> SELECT JSON_QUERY(@json,'$.x'), JSON_VALUE(@json,'$.x');
    +-------------------------+-------------------------+
    | JSON_QUERY(@json,'$.x') | JSON_VALUE(@json,'$.x') |
    +-------------------------+-------------------------+
    | [0,1]                   | NULL                    |
    +-------------------------+-------------------------+
    1 row in set (0.000 sec)

    MariaDB [test]> SELECT JSON_QUERY(@json,'$.y'), JSON_VALUE(@json,'$.y');
    +-------------------------+-------------------------+
    | JSON_QUERY(@json,'$.y') | JSON_VALUE(@json,'$.y') |
    +-------------------------+-------------------------+
    | NULL                    | [0,1]                   |
    +-------------------------+-------------------------+
    1 row in set (0.000 sec)

    MariaDB [test]> SELECT JSON_QUERY(@json,'$.z'), JSON_VALUE(@json,'$.z');
    +-------------------------+-------------------------+
    | JSON_QUERY(@json,'$.z') | JSON_VALUE(@json,'$.z') |
    +-------------------------+-------------------------+
    | NULL                    | Monty                   |
    +-------------------------+-------------------------+
    1 row in set (0.000 sec)

    MariaDB [test]> SELECT JSON_QUERY(@json,'$.x[0]'), JSON_VALUE(@json,'$.x[0]');
    +----------------------------+----------------------------+
    | JSON_QUERY(@json,'$.x[0]') | JSON_VALUE(@json,'$.x[0]') |
    +----------------------------+----------------------------+
    | NULL                       | 0                          |
    +----------------------------+----------------------------+
    1 row in set (0.000 sec)

    - JSON_ARRAY 함수
      10.2.3 버전부터 추가됨
      MariaDB [test]> SELECT Json_Array(56, 3.1416, 'My name is "Foo"', NULL);
    +--------------------------------------------------+
    | Json_Array(56, 3.1416, 'My name is "Foo"', NULL) |
    +--------------------------------------------------+
    | [56, 3.1416, "My name is \"Foo\"", null]         |
    +--------------------------------------------------+
    1 row in set (0.000 sec)


    MariaDB [test]> insert into json_test(id, data) values (4, JSON_ARRAY("Name","Ra, Ro ", "Sex", "F", "Phone", "010-1122-3344", "Birth", "1990-06-01"));
    Query OK, 1 row affected (0.003 sec)
 
     
    MariaDB [test]> select * from json_test;
    +------+-------------------------------------------------------------------------------------+---------------+
    | id   | data                                                                                | phone         |
    +------+-------------------------------------------------------------------------------------+---------------+
    |    1 | {"Name": "Su, Peng", "Sex": "M", "Phone": "010-3456-7890"}                          | 010-3456-7890 |
    |    2 | {"Name": "Dori Go", "Sex": "F", "Phone": "02-123-4567", "Birth": "2000-01-01"}      | 02-123-4567   |
    |    3 | {"Name": "DaHan, Wi ", "Sex": "M", "Phone": "010-9876-5432", "Birth": "1999-12-31"} | 010-9876-5432 |
    |    4 | ["Name", "Ra, Ro ", "Sex", "F", "Phone", "010-1122-3344", "Birth", "1990-06-01"]    | NULL          |
    +------+-------------------------------------------------------------------------------------+---------------+
    4 rows in set (0.000 sec)

    위의 id 4번 값은 아래에 보듯이 Type이 맞지 않기 때문에 phone값이 정상 인식 되지 않았음.
    
    MariaDB [test]> select json_type(data) from json_test;
    +-----------------+
    | json_type(data) |
    +-----------------+
    | OBJECT          |
    | OBJECT          |
    | OBJECT          |
    | ARRAY           |
    +-----------------+
    4 rows in set (0.001 sec)

    - 함수들 간략한 설명
    2
    JSON_QUERY와 JSON_VALUE의 차이점
        JSON_QUERY와 JSON_VALUE의 예제와 비교합니다.
    JSON_ARRAY
        나열된 값이 포함 된 JSON 배열을 반환합니다.
    JSON_ARRAY_APPEND
        JSON 문서 내에서 주어진 배열의 끝에 값을 추가합니다.
    JSON_ARRAY_INSERT
        JSON 문서에 값을 삽입합니다.
    JSON_COMPACT
        불필요한 모든 공간을 제거하여 json 문서가 가능한 한 짧습니다.
    JSON_CONTAINS
        지정된 JSON 문서 또는 문서 내의 지정된 경로에서 값을 찾을 수 있는지 여부
    JSON_CONTAINS_PATH
        지정된 JSON 문서에 지정된 경로의 데이터가 있는지 여부를 나타냅니다.
    JSON_DEPTH
        JSON 문서의 최대 깊이.
    JSON_DETAILED
        중첩 구조를 강조하는 가장 이해하기 쉬운 방식으로 JSON을 나타냅니다.
    JSON_EXISTS
        지정된 데이터에 지정된 JSON 값이 있는지 확인합니다. 
    JSON_EXTRACT
        JSON 문서에서 데이터를 추출합니다.
    JSON_INSERT
        JSON 문서에 데이터를 삽입합니다.
    JSON_KEYS
        JSON 객체의 최상위 값에서 키를 반환하거나 경로에서 최상위 키를 반환합니다.
        MariaDB [test]> select id, json_keys(data) from json_test;
        +------+-----------------------------------+
        | id   | json_keys(data)                   |
        +------+-----------------------------------+
        |    1 | ["Name", "Sex", "Phone"]          |
        |    2 | ["Name", "Sex", "Phone", "Birth"] |
        |    3 | ["Name", "Sex", "Phone", "Birth"] |
        |    4 | NULL                              |
        |    5 | NULL                              |
        +------+-----------------------------------+
        5 rows in set (0.000 sec)

    JSON_LENGTH
        JSON 문서의 길이 또는 문서 내 값의 길이를 반환합니다.
    JSON_LOOSE
        더 읽기 쉽게 보이도록 JSON 문서에 공백을 추가합니다.
    JSON_MERGE
        주어진 JSON 문서를 병합합니다.
    JSON_MERGE_PATCH
        주어진 JSON 문서의 RFC 7396 호환 병합
    JSON_MERGE_PRESERVE
        JSON_MERGE의 동의어
    JSON_OBJECT
        주어진 키 / 값 쌍을 포함하는 JSON 객체를 반환합니다. 
    JSON_QUERY
        JSON 문서가 주어지면 경로로 지정된 객체 또는 배열을 반환합니다.
    JSON_QUOTE
        문자열을 JSON 값으로 인용합니다.
    JSON_REMOVE
        JSON 문서에서 데이터를 제거합니다.
    JSON_REPLACE
        JSON 문서에서 기존 값을 바꿉니다.
    JSON_SEARCH
        JSON 문서 내에서 지정된 문자열의 경로를 반환합니다.
    JSON_SET
        JSON 문서에 데이터를 업데이트하거나 삽입합니다.
    JSON_TYPE
        JSON 값의 유형을 반환합니다.
    JSON_UNQUOTE
        JSON 값을 인용 해제하여 문자열을 반환합니다. 
    JSON_VALID
        값이 유효한 JSON 문서인지 여부 
    JSON_VALUE
        JSON 문서가 주어지면 지정된 스칼라를 반환합니다.
     

반응형

'Database > MYSQL' 카테고리의 다른 글

MariaDB connect 설치  (0) 2019.11.07
MariaDB 테이블 백업 및 복구  (0) 2019.11.01
MariaDB 우편번호 Import 하기  (0) 2019.11.01
MariaDB SHA2 512 방식으로 암호화 예제  (0) 2019.10.25
Mysql & MariaDB 튜닝 쉘  (0) 2019.08.14
반응형

File Writing 부분은 작성하지 않았음...

 

여러모로 문제가 있음

 

참고용...


import java.net.URLEncoder;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList; 
 
public class getMsrstnAcctoRltmMesureDnsty {
 

    // tag값의 정보를 가져오는 메소드
private static String getTagValue(String tag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(tag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);
    if(nValue == null) 
        return null;
    return nValue.getNodeValue();
}

public static void main(String[] args) {
int page = 1; // 페이지 초기값 
     int totalCount = 0; // 전체 건수
    
     int nowCnt = 0; // 현재 페이지의 건수
    
     // JSON Object 
     JSONArray jitem = new JSONArray(); 
    
    
    
try{
while(true){

 // 서비스 인증키입니다. 공공데이터포털에서 제공해준 인증키를 넣어주시면 됩니다.         
            String serviceKey = "키입력";
             
             
            // 한페이지에서 읽어올 개수
            String numOfRows   = "5";         
            
            // 한글은 encoding 수행합니다.
         String stationName = URLEncoder.encode("종로구", "UTF-8");
         String ver         = "1.0";
         String dataTerm    = "DAILY";
         String RtnType     = "XML";
    
     StringBuffer jsonSb = null;
        
        
            String urlStr = "http://openapi.airkorea.or.kr/"
                    + "openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty"
                    + "?"
                    + "ServiceKey="  + serviceKey
                    + "&stationName=" + stationName
                    + "&dataTerm="  + dataTerm 
                    + "&pageNo=" + page
                    + "&numOfRows=" + numOfRows                    
                    + "&ver=" + ver 
                    + "&_retrunType=" + RtnType
                    ;
            
DocumentBuilderFactory dbFactoty = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactoty.newDocumentBuilder(); 
Document doc = dBuilder.parse(urlStr);



if ( page == 1 ) { 
// 파싱할 tag
NodeList nListT = doc.getElementsByTagName("body");

Node nNodeT = nListT.item(0);
if(nNodeT.getNodeType() == Node.ELEMENT_NODE){

Element eElementT = (Element) nNodeT; 

totalCount = Integer.parseInt(getTagValue("totalCount", eElementT));
} // for end

}

// root tag 
doc.getDocumentElement().normalize();  

// 파싱할 tag
NodeList nList = doc.getElementsByTagName("item");


//JSONObject
for(int temp = 0; temp < nList.getLength(); temp++){
Node nNode = nList.item(temp);
if(nNode.getNodeType() == Node.ELEMENT_NODE){

Element eElement = (Element) nNode;

JSONObject jobj = new JSONObject();


jobj.put("dataTime",  getTagValue("dataTime", eElement).toString());
// jobj.put("so2Value",  Float.parseFloat(getTagValue("so2Value", eElement).toString()));
// jobj.put("coValue",   Float.parseFloat(getTagValue("coValue", eElement).toString()));
// jobj.put("o3Value",   Float.parseFloat(getTagValue("o3Value", eElement).toString()));
// jobj.put("pm10Value", Float.parseFloat(getTagValue("pm10Value", eElement).toString()));
// jobj.put("pm25Value", Float.parseFloat(getTagValue("pm25Value", eElement).toString()));
// jobj.put("khaiValue", Float.parseFloat(getTagValue("khaiValue", eElement).toString()));
// jobj.put("khaiGrade", Float.parseFloat(getTagValue("khaiGrade", eElement).toString()));
// jobj.put("so2Grade",  Float.parseFloat(getTagValue("so2Grade", eElement).toString()));
// jobj.put("coGrade",   Float.parseFloat(getTagValue("coGrade", eElement).toString()));
// jobj.put("o3Grade",   Float.parseFloat(getTagValue("o3Grade", eElement).toString()));
// jobj.put("no2Grade",  Float.parseFloat(getTagValue("no2Grade", eElement).toString()));
// jobj.put("pm10Grade", Float.parseFloat(getTagValue("pm10Grade", eElement).toString()));
// jobj.put("pm25Grade", Float.parseFloat(getTagValue("pm25Grade", eElement).toString()));

jobj.put("so2Value",  getTagValue("so2Value", eElement).toString());
jobj.put("coValue",   getTagValue("coValue", eElement).toString());
jobj.put("o3Value",   getTagValue("o3Value", eElement).toString());
jobj.put("pm10Value", getTagValue("pm10Value", eElement).toString());
jobj.put("pm25Value", getTagValue("pm25Value", eElement).toString());
jobj.put("khaiValue", getTagValue("khaiValue", eElement).toString());
jobj.put("khaiGrade", getTagValue("khaiGrade", eElement).toString());
jobj.put("so2Grade",  getTagValue("so2Grade", eElement).toString());
jobj.put("coGrade",   getTagValue("coGrade", eElement).toString());
jobj.put("o3Grade",   getTagValue("o3Grade", eElement).toString());
jobj.put("no2Grade",  getTagValue("no2Grade", eElement).toString());
jobj.put("pm10Grade", getTagValue("pm10Grade", eElement).toString());
jobj.put("pm25Grade", getTagValue("pm25Grade", eElement).toString());

  JSONParser jsonParser = new JSONParser();
jitem.add(jsonParser.parse(jobj.toJSONString()));

    
} // for end
} // if end



nowCnt = page * Integer.parseInt(numOfRows);

page += 1;

 
if(nowCnt > totalCount){
break;
}
} // while end

} catch (Exception e){
e.printStackTrace();
} // try~catch end

System.out.println("[message]:" + jitem.toJSONString());
System.out.println("End of Main");
} // main end 
   
  }
   


반응형

'4차 산업 > ELK 관련' 카테고리의 다른 글

Logstash 대기 오염 관련 Json 처리 예제  (0) 2019.03.21
반응형

input {

  file {

    type => "json"

    codec => "json" {

        charset => "utf-8"

    }

    path => "/test.json"

    start_position => "beginning"

    sincedb_path => "/dev/null"

  }

}

filter {

  json {

   source => "message"

  }


  # split records tag

  split {

        field => "[records]"

  }


  # new json type append

  if [records][so2Grade] {

  mutate {

        add_field => {

                "so2Grade"    => "%{[records][so2Grade]}"

                "pm25Grade1h" => "%{[records][pm25Grade1h]}"

                "pm10Value24" => "%{[records][pm10Value24]}"

                "khaiValue"   => "%{[records][khaiValue]}"

                "so2Value"    => "%{[records][so2Value]}"

                "coValue"     => "%{[records][coValue]}"

                "pm10Grade1h" => "%{[records][pm10Grade1h]}"

                "o3Grade"     => "%{[records][o3Grade]}"

                "pm10Value"   => "%{[records][pm10Value]}"

                "khaiGrade"   => "%{[records][khaiGrade]}"

                "pm25Value"   => "%{[records][pm25Value]}"

                "no2Grade"    => "%{[records][no2Grade]}"

                "pm25Value24" => "%{[records][pm25Value24]}"

                "pm25Grade"   => "%{[records][pm25Grade]}"

                "mangName"    => "%{[records][mangName]}"

                "coGrade"     => "%{[records][coGrade]}"

                "dataTime"    => "%{[records][dataTime]}"

                "no2Value"    => "%{[records][no2Value]}"

                "pm10Grade"   => "%{[records][pm10Grade]}"

                "o3Value"     => "%{[records][o3Value]}"

        }


        # remove split records

        remove_field => [ "[fields]", "[records]" ]

  }


   # convert field

   mutate {

       convert => {

         "so2Grade"    => "float"

         "pm25Grade1h" => "float"

         "pm10Value24" => "float"

         "khaiValue"   => "float"

         "so2Value"    => "float"

         "coValue"     => "float"

         "pm10Grade1h" => "float"

         "o3Grade"     => "float"

         "pm10Value"   => "float"

         "khaiGrade"   => "float"

         "pm25Value"   => "float"

         "no2Grade"    => "float"

         "pm25Value24" => "float"

         "pm25Grade"   => "float"

         "coGrade"     => "float"

         "no2Value"    => "float"

         "pm10Grade"   => "float"

         "o3Value"     => "float"

         "mangName"    => "string"

      }

   }

}

output {

    stdout { codec => json }

    file {

        codec => json_lines

        path => "/output_test.json"

    }

    elasticsearch {

       hosts => "localhost"

       index => "atmosphere"

    }

}


======================================================


input {

  file {

    type           => "json"

    #codec          => "json"

    codec          => "plain"

    path           => "/media/sf_Class/jptest/jongrogu20190320.json"

    start_position => "beginning"

    sincedb_path   => "/dev/null"

  }

}

filter {

  json {

        source => "message"

  }


  # split records tag

  split {

        field => "[records]"

  }


  # new json type append

  mutate {

        # remove split records

        remove_field => [ "[fields]", "[records]" ]

        add_field => {

                "so2Grade"    => "%{[records][so2Grade]}"

                "pm25Grade1h" => "%{[records][pm25Grade1h]}"

                "pm10Value24" => "%{[records][pm10Value24]}"

                "khaiValue"   => "%{[records][khaiValue]}"

                "so2Value"    => "%{[records][so2Value]}"

                "coValue"     => "%{[records][coValue]}"

                "pm10Grade1h" => "%{[records][pm10Grade1h]}"

                "o3Grade"     => "%{[records][o3Grade]}"

                "pm10Value"   => "%{[records][pm10Value]}"

                "khaiGrade"   => "%{[records][khaiGrade]}"

                "pm25Value"   => "%{[records][pm25Value]}"

                "no2Grade"    => "%{[records][no2Grade]}"

                "pm25Value24" => "%{[records][pm25Value24]}"

                "pm25Grade"   => "%{[records][pm25Grade]}"

                "mangName"    => "%{[records][mangName]}"

                "coGrade"     => "%{[records][coGrade]}"

                "dataTime"    => "%{[records][dataTime]}"

                "no2Value"    => "%{[records][no2Value]}"

                "pm10Grade"   => "%{[records][pm10Grade]}"

                "o3Value"     => "%{[records][o3Value]}"

        }


  }


 # validation

  mutate {

           gsub =>  [

                       "so2Grade" ,    "[^0-9.]" , "",

                       "pm25Grade1h" , "[^0-9.]" , "",

                       "pm10Value24" , "[^0-9.]" , "",

                       "khaiValue" ,   "[^0-9.]" , "",

                       "so2Value" ,    "[^0-9.]" , "",

                       "coValue" ,     "[^0-9.]" , "",

                       "pm10Grade1h" , "[^0-9.]" , "",

                       "o3Grade" ,     "[^0-9.]" , "",

                       "pm10Value" ,   "[^0-9.]" , "",

                       "khaiGrade" ,   "[^0-9.]" , "",

                       "pm25Value" ,   "[^0-9.]" , "",

                       "no2Grade"  ,   "[^0-9.]" , "",

                       "pm25Value24" , "[^0-9.]" , "",

                       "pm25Grade" ,   "[^0-9.]" , "",

                       "coGrade" ,     "[^0-9.]" , "",

                       "no2Value" ,    "[^0-9.]" , "",

                       "pm10Grade" ,   "[^0-9.]" , "",

                       "o3Value" ,     "[^0-9.]" , ""

                    ]

  }




  # convert field

  mutate {

       convert => {

         "so2Grade"    => "float"

         "pm25Grade1h" => "float"

         "pm10Value24" => "float"

         "khaiValue"   => "float"

         "so2Value"    => "float"

         "coValue"     => "float"

         "pm10Grade1h" => "float"

         "o3Grade"     => "float"

         "pm10Value"   => "float"

         "khaiGrade"   => "float"

         "pm25Value"   => "float"

         "no2Grade"    => "float"

         "pm25Value24" => "float"

         "pm25Grade"   => "float"

         "coGrade"     => "float"

         "no2Value"    => "float"

         "pm10Grade"   => "float"

         "o3Value"     => "float"

      }

   }


  # date

  date {

        match => ["dataTime" , "yyyy-MM-dd HH:mm"]

  }


}



output {

    stdout { codec => rubydebug }

    file {

        codec => json_lines

        path => "/media/sf_Class/jptest/output_test.json"

    }

#    elasticsearch {

#       hosts => "localhost"

#       index => "atmosphere"

#    }

}




반응형

+ Recent posts