ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • elasticsearch 시작하기 - bulk index 로 색인하기
    프로그래밍/검색 2015. 12. 29. 05:28
    반응형

     

     

    기본 사용법

     

    D:\es\elasticsearch-1.4.2>curl -s -XPOST "http://localhost:9200/_bulk" --data-binary @bulkdata.json

     

    --data-binary 옵션뒤에 색인할 bulk file을 지정한다.

    bulk 색인중에는 bulk file이 다 메모리에 로드되기 때문에

    적은 사이즈 (20~30 M)로 나눠서 색인을 하도록 색인 스크립트를 작성하였다.

     

     

    Linux -command 


    D:\es\elasticsearch-1.4.2>curl -s -XPOST "http://localhost:9200/_bulk" --data-binary @bulkdata.json


     

     

    리눅스에서는 주소에 ' 나 "를 붙여도 잘 되지만 윈도우에서는 에러가 나거나 작동 안함


    윈도우 - command line


    D:\es\elasticsearch-1.6.0\bin>curl -s -XPOST "localhost:9200/_bulk" --data-binary @bulkdata.json

    {"error":"ElasticsearchParseException[Failed to derive xcontent from org.elastic

    search.common.bytes.BytesArray@1]","status":400}


    D:\es\elasticsearch-1.6.0\bin>curl -s -XPOST 'localhost:9200/_bulk' --data-binary @bulkdata.json

    작동안함


    D:\es\elasticsearch-1.6.0\bin>curl -s -XPOST localhost:9200/_bulk --data-binary@bulkdata.json

    제대로 동작


     

     

    bulk file (예시)

    {"index":{"_index":"indexname","_type":"typename","_id":"1"}}
    {"id":"981146","날짜":"2014-01-01",... ,"총주식수":null}

     

    - doc이후의 마지막 라인에 빈 라인이 있지 않으면 no_requests added 에러가 나니 조심할 것. (참고:

    http://stackoverflow.com/questions/22996337/elasticsearch-no-requests-added-bulk-api-error)

     

    { "error": "ActionRequestValidationException[Validation Failed: 1: no requests added;]", "status": 500 }

     

     

    리눅스 전체 bulk index 스크립트

     

     

    #!/bin/sh


    today=`date '+%Y%m%d'`
    jsondir=/home/json/$today
    bulkdir=/home/bulk/$today
    mkdir ${jsondir}
    mkdir ${bulkdir}

    // table에서 bulk file을 생성하는 스크립트
    php extract_bulk_from_table.php > ${jsondir}/bulkdata.json
    split_bulk.sh 200000 ${jsondir}/bulkdata.json
    curl -XDELETE localhost:9200/indexname

    // mapping 설정
    curl -s -XPOST 'http://localhost:9200/indexname' --data-binary @mapping_unit.json

    for entry in $bulkdir/*
    do
            echo "$entry"
            curl -s -XPOST 'http://localhost:9200/_bulk' --data-binary @${entry}
    done


     

    extract_bulk_from_table.php

     

    <?php

    ini_set('memory_limit', '-1');
    header("Content-Type: text/html; charset=UTF-8");
    $conn = mysqli_connect('localhost', 'id', 'passwd','dbname');
    if (mysqli_connect_errno($conn))
    {
            echo "데이터베이스 연결 실패: " . mysqli_connect_error();
    }
     

      $check_query = "select * from tablename";

      $result = $conn->query($check_query);

      $total_line = "";
      while($row = mysqli_fetch_assoc($result)) {

                       $type = $row['종목코드'];
                       $total_line = "{\"index\":{\"_index\":\"indexname\",\"_type\":\"".$type."\",\"_id\":\"".$id++."\"}}\n";
                       $total_line .= json_encode($row, JSON_UNESCAPED_UNICODE );
                       $total_line .= "\n";
                       echo $total_line;
                    }


     

    ?>

     

     

    mapping_unit.json

     

    {
        "settings" : {
          "analysis": {
              "filter": {
                "my_shingle_filter": {
                   "type": "shingle",
                   "output_unigrams": false
                }
              },
              "analyzer" : {
                "my_shingle_analyzer": {
                   "type": "custom",
                   "tokenizer" : "standard",
                   "filter": [
                      "my_shingle_filter"
                   ]
                }
              }
          }
        },
        "mappings" : {
          "_default_" : {
            "properties" : {
              "4일종가합" : {
                "type" : "string"
              },

              "종목" : {
                "type" : "string",
                "index" : "not_analyzed"
              },
              ....  
              "현재가" : {
                "type" : "string"
              }
            }
          }
    }
    }

     

     


    728x90
    반응형
Designed by Tistory.