<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python &#8211; WONIZZ.LOG</title>
	<atom:link href="https://blog.wonizz.com/category/tech/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.wonizz.com</link>
	<description>AI 자동화를 직접 굴려 본 개발자의 실무 교훈</description>
	<lastBuildDate>Fri, 21 Aug 2026 15:44:45 +0000</lastBuildDate>
	<language>ko-KR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0.2</generator>

<image>
	<url>https://i0.wp.com/blog.wonizz.com/wp-content/uploads/2026/08/wz-siteicon-512.png?fit=32%2C32&#038;ssl=1</url>
	<title>Python &#8211; WONIZZ.LOG</title>
	<link>https://blog.wonizz.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">152411368</site>	<item>
		<title>[DevOps] ElasticSearch to CSV export</title>
		<link>https://blog.wonizz.com/2022/03/07/devops-elasticsearch-to-csv-export/</link>
					<comments>https://blog.wonizz.com/2022/03/07/devops-elasticsearch-to-csv-export/#respond</comments>
		
		<dc:creator><![CDATA[워니즈]]></dc:creator>
		<pubDate>Mon, 07 Mar 2022 04:26:23 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tech]]></category>
		<guid isPermaLink="false">https://blog.wonizz.tk/?p=1881</guid>

					<description><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
<p>안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 ElasticSearch의 데이터를 CSV로 export 하는 내용에 대해서 정리를 해보겠습니다. 필자는 DevOps 업무를 하고 있습니다. 그러다보니 최대한 자동화를 통해서 업무를 효율적으로 하는 부분에 대해서도 신경을 많이 쓰고 있습니다. 어느날인가 개발팀분이 저에게 DM을 주셔서 elasticsearch to csv가 가능한지 문의가 들어왔습니다. 하지만 필자도 그동안 ES에 대한 데이터 적재 및 대시보드 구성만 해봤었고 export&#8230;&#160;</p>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/03/07/devops-elasticsearch-to-csv-export/">[DevOps] ElasticSearch to CSV export</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>The standard Lorem Ipsum passage, used since the 1500s<br />
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
<p>Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"</p>
<p>1914 translation by H. Rackham<br />
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</p>
<p>Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC<br />
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."</p>
<p>1914 translation by H. Rackham<br />
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>
안녕하세요? 정리하는 개발자 워니즈입니다. 이번시간에는 <strong>ElasticSearch</strong>의 데이터를 <strong>CSV</strong>로 export 하는 내용에 대해서 정리를 해보겠습니다.

필자는 DevOps 업무를 하고 있습니다. 그러다보니 최대한 자동화를 통해서 업무를 효율적으로 하는 부분에 대해서도 신경을 많이 쓰고 있습니다.

어느날인가 개발팀분이 저에게 DM을 주셔서 elasticsearch to csv가 가능한지 문의가 들어왔습니다. 하지만 필자도 그동안 ES에 대한 데이터 적재 및 대시보드 구성만 해봤었고 export 시키는 내용에 대해서는 정확하게 알지를 못했습니다 .

ES도 결국 DB와 같은 데이터 record를 적재하고 있고, 이런 부분들을 query를 통해서 충분히 가져올 수 있을 것이라고 생각했습니다.

관련해서 위의 내용을 정리해보도록 하겠습니다.

<img decoding="async" src="https://miro.medium.com/max/1400/0*Xhz01Vby2rg86xZj" alt="DevOps ElasticSearch to CSV export 설명 이미지 1" />

<h2>1. ES query 호출해보기</h2>

우선 간단하게나마 ES를 호출해보기로했습니다. 그러기 위해서는 ES에 query를 하는 방식을 이해해야 합니다. 필자가 요구하는 사항은 각 Index별로 전체의 데이터를 가져오는 것이기 때문에 전체 조회 query를 확인했습니다.

<ul>
<li>Match_all / match_nonde</li>
</ul>

match_all 쿼리는 지정된 index의 모든 document를 검색하는 방법입니다.즉, 특별한 검색어 없이 모든 document를 가져오고 싶을 때 사용합니다.SQL로 치면 WHERE 절이 없는 SELECT문과 같습니다.

<pre><code class="language-json line-numbers">{  
   "query":{  
      "match_all":{}
   }
}
</code></pre>

그런데 위처럼 조회를 하면 결과가 전체 records를 가져오지 않고 return 하는 records가 전체보다는 작은 수치였습니다. 
<a class="wp-editor-md-post-content-link" href="https://stackoverflow.com/questions/8829468/elasticsearch-query-to-return-all-records" target="_blank" rel="noopener">Elasticsearch query to return all records</a>

위의 내용을 확인하여, <strong>size</strong>값을 추가하기로 했습니다.

<pre><code class="language-json line-numbers">{  
   "size": 1000,
   "query":{  
      "match_all":{}
   }
}
</code></pre>

인덱스별로 최대 1000을 넘지 않는것을 확인 한 뒤, 위와 같이 size값을 주어, 전체 레코즈를 가져올 수 있도록 설정했습니다.

<h2>2. python을 활용한 호출부 구현</h2>

위의 내용으로 하나의 Index에 대해서 전체 데이터를 가져오는 부분을 구현해보기로했습니다.

<pre><code class="language-python line-numbers">    headers = {
        'authority': '{ES 주소}',
        'authorization': 'Basic {계정 정보}',
        'content-type': 'application/json',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',
    }
    params = (
        ('path', index+'/_search'),
        ('method', 'POST'),
    )

    ## query 요청 
    json_data = {
        'size': 1000,
        'query': {
            'match_all': {},
        },
    }
    response = requests.post('{ES 주소}/api/console/proxy', headers=headers, params=params, json=json_data)
</code></pre>

위와 같이 호출하니 정상적으로 데이터를 받아왔습니다. 위의 내용을 함수로 구현하여 인덱스에 대해서 레코즈를 가져오는 부분으로 구현했습니다.

<h2>3. ES Index list 가져오기</h2>

상위 작업에서 인덱스를 파라미터로 넣으면, 전체 레코즈를 가져오도록 설계를 했습니다. 이제는 전체 ES 리스트를 조회하고 파라미터를 준비하기로했습니다.

ES의 query builder에서 <strong>DEV Tools</strong>를 통해서 전체 index를 가져오는 내용을 호출했습니다.

<pre><code class="language-json line-numbers">GET /_cat/indices?v
</code></pre>

위와 같이 호출을 하게 되면, 마치 Excel의 Sheet 형식으로 데이터가 리턴이 됩니다. 거기서 필요한 인덱스 정보만을 취득하여 파라미터로 준비하기로해습니다.

<h2>4. pandas를 이용한 CSV export</h2>

위에서 Index List를 통해서 한개의 Index에 해당하는 모든 레코즈를 가져오도록 설계를 했습니다. 그리고 이내용을 json파일로 만들어서 저장하도록 했습니다.

<strong>Python</strong>의 <strong>pandas</strong>를 이용해서 json 데이터를 읽고 해당 내용을 CSV로 변환하기로했습니다.

<pre><code class="language-python line-numbers">import pandas as pd

# json file read
def read_json(filename: str) -> dict:
    try:
        with open(filename, "r") as f:
            data = json.loads(f.read())
    except:
        raise Exception(f"Reading {filename} file encountered an error")
    return data

def create_dataframe(data: list) -> pd.DataFrame:
    # Declare an empty dataframe to append records
    dataframe = pd.DataFrame()
    # Looping through each record
    for d in data:
        # Normalize the column levels
        record = pd.json_normalize(d)
        # Append it to the dataframe
        dataframe = dataframe.append(record, ignore_index=True)
    return dataframe

# pandas json to csv
data = read_json(filename="result-1.json")
dataframe = create_dataframe(data=data)
dataframe.to_csv("result.csv", index=False)

</code></pre>

마지막 세줄이 제일 중요합니다.

<pre><code class="language-python line-numbers">data = read_json(filename="result-1.json")
</code></pre>

json파일을 읽고 data라는 변수에 할당합니다.

<pre><code class="language-python line-numbers">dataframe = create_dataframe(data=data)
</code></pre>

pandas를 통해서 위에서 읽은 data 변수를 파라미터로 넣고 해당 내용을 dataframe으로 만들어줍니다.

<pre><code class="language-python line-numbers">dataframe.to_csv("result.csv", index=False)
</code></pre>

위에서 읽은 dataframe형태를 CSV 파일로 export하면서 최종 완료합니다.

<h2>5. 최종 아키텍처</h2>

<pre><code class="language-python line-numbers">import requests
import json
from time import sleep
import pandas as pd

resultArray = []

# ES http request를 통한 데이터 획득
def getDataFromES(index) :
    headers = {
        'authority': '{ES 주소}',
        'authorization': 'Basic {ES 계정}',
        'content-type': 'application/json',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'cors',
        'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',
    }
    params = (
        ('path', index+'/_search'),
        ('method', 'POST'),
    )

    ## query 요청 
    json_data = {
        'size': 1000,
        'query': {
            'match_all': {},
        },
    }
    response = requests.post('{ES 주소}/api/console/proxy', headers=headers, params=params, json=json_data)

    sleep(1)
    print(index + " 완료")
    return response

# 2depth의 json을 nomalize 하는 함수.
def normalize_json(data: dict) -> dict:
    new_data = dict()
    for key, value in data.items():
        if not isinstance(value, dict):
            new_data[key] = value
        else:
            for k, v in value.items():
                new_data[key + "_" + k] = v
    return new_data


# json file read
def read_json(filename: str) -> dict:
    try:
        with open(filename, "r") as f:
            data = json.loads(f.read())
    except:
        raise Exception(f"Reading {filename} file encountered an error")
    return data


def create_dataframe(data: list) -> pd.DataFrame:
    # Declare an empty dataframe to append records
    dataframe = pd.DataFrame()
    # Looping through each record
    for d in data:
        # Normalize the column levels
        record = pd.json_normalize(d)
        # Append it to the dataframe
        dataframe = dataframe.append(record, ignore_index=True)
    return dataframe


#index 리스트 
indexList = ['sample-index-2020-08-25',
'sample-index-2020-08-26',]

# resultArray객체에 모든 jsonobject 추가.
for index in indexList:
    result = getDataFromES(index)
    jsonObject= json.loads(result.text)
    jsonArray = jsonObject.get("hits").get("hits")

    for list in jsonArray:
        new_data = normalize_json(data=list)
        resultArray.append(new_data)


f = open("result-1.json", "w")
f.write(json.dumps(resultArray))
f.close()

# pandas json to csv
data = read_json(filename="result-1.json")
dataframe = create_dataframe(data=data)
dataframe.rename(columns={}, inplace=True)

dataframe.to_csv("result.csv", index=False)


</code></pre>

최종코드는 위와 같고, 위의 내용을 그림으로 표현한 내용은 아래와 같습니다.

<img decoding="async" src="/Users/user/업무/3_기타/01.블로그이미지/20220225/pandas_1.png" alt="DevOps ElasticSearch to CSV export 설명 이미지 2" />

<h2>6. 마치며..</h2>

간단한 프로그램을 통해서 전체 ES의 데이터를 export하는 프로그램을 만들어봤습니다. 간단하지만 csv로 export를 통해서 무엇인가를 자동화한거 같아서 매우 뿌듯하면서도 재밌었습니다.

다음시간에는 pandas에 대해서도 정리를 해보는 시간을 갖도록 하겠습니다.

<h2>7. 참고</h2>

<a class="wp-editor-md-post-content-link" href="https://www.geeksforgeeks.org/convert-nested-json-to-csv-in-python/" target="_blank" rel="noopener">convert nested json to csv in python</a>
<h2 class="wp-block-heading">함께 보면 좋은 글</h2>
<ul class="wp-block-list"><li><a href="https://blog.wonizz.com/2024/08/21/devops-ios-build-pipeline/">[DevOps] IOS 빌드 파이프라인 구성</a></li><li><a href="https://blog.wonizz.com/2024/07/24/devops-kubernetes-hpa/">[DevOps] Kubernetes HPA 실전 적용</a></li><li><a href="https://blog.wonizz.com/2024/07/18/devops-nginx-lua-module/">[DevOps] Nginx Lua module 사용법</a></li><li><a href="https://blog.wonizz.com/2023/11/03/devops-nginx-rate-limit/">[DevOps] Nginx Rate Limit</a></li></ul>
<p>The post <a rel="nofollow" href="https://blog.wonizz.com/2022/03/07/devops-elasticsearch-to-csv-export/">[DevOps] ElasticSearch to CSV export</a> appeared first on <a rel="nofollow" href="https://blog.wonizz.com">WONIZZ.LOG</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.wonizz.com/2022/03/07/devops-elasticsearch-to-csv-export/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1881</post-id>	</item>
	</channel>
</rss>
