<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Stanislav Prihoda 🔥 on Medium]]></title>
        <description><![CDATA[Stories by Stanislav Prihoda 🔥 on Medium]]></description>
        <link>https://medium.com/@stanislavprihoda?source=rss-6957ec4490d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_T1x5v05p1bH03vTUth5FQ.png</url>
            <title>Stories by Stanislav Prihoda 🔥 on Medium</title>
            <link>https://medium.com/@stanislavprihoda?source=rss-6957ec4490d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:21:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stanislavprihoda/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From scratch to search: playing with your data (Elasticsearch Ingest Pipelines)]]></title>
            <link>https://medium.com/data-science/from-scratch-to-search-playing-with-your-data-elasticsearch-ingest-pipelines-6d054bf5d866?source=rss-6957ec4490d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d054bf5d866</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Stanislav Prihoda ]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 16:06:15 GMT</pubDate>
            <atom:updated>2020-01-16T17:04:58.286Z</atom:updated>
            <content:encoded><![CDATA[<h4>One Pipeline to rule them all, One Pipeline to ingest them, One Pipeline to transform them all and in the Elasticsearch bind them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UYAOkAd90wQHutBp" /><figcaption>Photo by <a href="https://unsplash.com/@jvillella?utm_source=medium&amp;utm_medium=referral">Julian Villella</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>In this article I would like to quickly go through one interesting feature (of many) offered by Elasticsearch that I tend to use also in production setups which are the Ingest Pipelines. This feature allows to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/ingest.html"><em>pre-process documents</em></a><em> before the actual document indexing happens</em>. Sounds interesting, what for…</p><pre><strong><em>Note: for an introductory hands-on overview of the Elasticsearch technology check out </em></strong><a href="https://towardsdatascience.com/from-scratch-to-search-setup-elasticsearch-under-4-minutes-load-a-csv-with-python-and-read-e31405d244f1"><strong><em>my previous article</em></strong></a><strong><em>.</em></strong></pre><p>This can be useful in many ways but I can see two main reasons. Firstly, when you are more on the (big) data analytics/processing side, your priorities (and mandate) are likely not set to involve active changing of the source systems. So you have to deal with the raw data as they come and preprocess them to fit your data needs. Secondly, even if you intend to change the producers you A) may not have all under direct control (eg. due to some organisational aspects, their legacy nature eg.) and/or B) still need to be prepared that the change may take quite a while (eg. think of tens/hundreds of microservices you want to upgrade on a new version of the your shared logging library etc.).</p><p>For these cases you can call to service the ingest pipelines.</p><h3>How does it work</h3><p>The ingest pipelines are newer player in the field of data parsing and transformations long occupied by <a href="https://www.elastic.co/products/logstash">Logstash</a>. Ingest pipelines are actually <a href="https://www.elastic.co/blog/should-i-use-logstash-or-elasticsearch-ingest-nodes">not a full replacement</a> of Logstash. But the consideration with Logstash is that it inevitably brings another sw component to your architecture thus making it more complicated to operate. This is not the case for the ingest pipelines as these are executed directly by any (or all) of the regular Elasticsearch <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-node.html">nodes</a> in your cluster. The node just needs to be of the type of <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html">Ingest node</a> (which is by default) so you don’t even need to mess with the configuration when you want to start using them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GUE1YHCC9Ye4lPwa" /><figcaption>Execution of pipelines on the ingest node happens right after the receival of the request by the coordinator node during the indexing operation. Image source: <a href="https://www.elastic.co/pdf/elasticsearch-sizing-and-capacity-planning.pdf">elastic.co</a>.</figcaption></figure><h3>Pipeline definition</h3><p>Generally the pipelines are defined via a simple <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/pipeline.html">JSON document</a> that contains an array of processors which represent an ordered set of steps that are applied and executed on all incoming documents. Actual processors come in various flavours so I highly recommend to crawl through <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/ingest-processors.html">their list in the docs</a> to get familiar.</p><p>Processors share some things in common. These are:</p><ul><li>ability to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/accessing-data-in-pipelines.html">access/reference data</a> of the processed document in the definition using curly brackets template {{service-name}}</li><li>ability to define <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/ingest-conditionals.html">conditional execution</a> of the processor with the <em>if</em> clause allowing to perform the step only after check of the conditions</li><li>ability to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/handling-failure-in-pipelines.html">handle failure of the processors</a> with <em>on_failure</em> clause</li><li>can be tagged via the <em>tag</em> clause which can be useful eg. for error tracing</li></ul><p>More on these later.</p><h3>Testing environment spin-up</h3><p>Enough of theory, let’s spin up a simple (single node) cluster in Docker on our local machine and try out a first pipeline definition. <em>Note: if you need more info on the docker part find it in </em><a href="https://towardsdatascience.com/from-scratch-to-search-setup-elasticsearch-under-4-minutes-load-a-csv-with-python-and-read-e31405d244f1"><em>my previous article</em></a><em>.</em> Let’s do also an instance of Kibana to have a simple GUI for review.</p><pre>#!/bin/bash</pre><pre>docker network create elastic-network</pre><pre>docker run --rm --detach --name elastic4pipelines -p 9200:9200 -v esdata01:/usr/share/elasticsearch/data --network elastic-network -e &quot;node.name=elastic4pipelines&quot; -e &quot;discovery.type=single-node&quot; -e &quot;bootstrap.memory_lock=true&quot; --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=&quot;-Xms2g -Xmx2g&quot; docker.elastic.co/elasticsearch/elasticsearch:7.5.1</pre><pre>docker run --rm --detach --link elastic4pipelines:elasticsearch --name kibana4pipelines --network elastic-network -p 5601:5601 docker.elastic.co/kibana/kibana:7.5.1</pre><p>When you run the script above and wait couple of minutes your temporary elastic stack should spin up and be ready for our pipeline tests (with Kibana running on <a href="http://localhost:5601/">http://localhost:5601/</a>).</p><h3>Processing documents with pipelines</h3><p>To test it we’ll start small and create a pipeline that will:</p><ul><li>split the value of one filed by specific delimiter with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/split-processor.html">Split Processor</a></li><li>in next step iterating through all values of the new array with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/foreach-processor.html">Foreach Processor</a> and converting to uppercase characters with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/uppercase-processor.html">Uppercase Processor</a></li></ul><pre>curl -XPUT localhost:9200/_ingest/pipeline/my_simple_pipeline \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>    &quot;processors&quot;: [<br>        {<br>            &quot;split&quot;: {<br>                &quot;field&quot;: &quot;meta.tags&quot;,<br>                &quot;separator&quot;: &quot; &quot;,<br>                &quot;target_field&quot;: &quot;meta.tags_parsed&quot;,<br>                &quot;ignore_missing&quot;: true<br>            }<br>        },<br>        {<br>            &quot;foreach&quot;: {<br>                &quot;field&quot;: &quot;meta.tags_parsed&quot;,<br>                &quot;processor&quot;: {<br>                    &quot;uppercase&quot;: {<br>                        &quot;field&quot;: &quot;_ingest._value&quot;<br>                    }<br>                }<br>            }<br>        }<br>    ]<br>}&#39;</pre><p>Now let’s create an index that will use this pipeline as its default ingest pipeline.</p><pre>curl -XPUT localhost:9200/my_index \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>    &quot;settings&quot;: {<br>        &quot;index.default_pipeline&quot;: &quot;my_simple_pipeline&quot;<br>    }<br>}&#39;</pre><p>Finally let’s index a dummy document that will be processed by this pipeline.</p><pre>curl -XPOST localhost:9200/my_index/_doc \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>    &quot;comment&quot;: &quot;I liked this article on pipelines!&quot;,<br>    &quot;meta&quot;: {<br>        &quot;tags&quot;: &quot;good enjoyed recommended&quot;<br>    }<br>}&#39;</pre><p>Now we can take a look on the document in Kibana. <em>Note: don’t forget to create an index pattern. </em>We can see the transformations in place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YN4YIU6gyU5CrpzfFmBdoQ.png" /></figure><h3>Scripting and conditional execution based on a value</h3><p>No let’s try two things and to be effective let’s use them both in one processor :)</p><ul><li>conditional execution using if clause (which is possible for all of the processors)</li><li>and more complex processing with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/script-processor.html">Script Processor</a> (when premade processors are not enough)</li></ul><p>Both of these use a Painless scripting language (which is based on Groovy). Read the <a href="https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-guide.html">painless guide</a> for more info. Nevertheless important is that:</p><ul><li>your processed document can be accessed in scripts via the ctx variable (so called <a href="https://www.elastic.co/guide/en/elasticsearch/painless/master/painless-ingest-processor-context.html">ingest processor context</a>)</li><li>ctx contains Map structure of the extracted JSON (reference the individual fields by square braces ctx[&#39;my_field&#39;])</li><li>you can modify the values of ctx variable to add, modify, or delete the fields of the document</li></ul><p>Simple example: we can use this to index only a part (substring) of the original text if rest is useless for our purposes. So just replace the pipeline…</p><pre>curl -XPUT localhost:9200/_ingest/pipeline/my_simple_pipeline \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>    &quot;processors&quot;: [<br>        {<br>            &quot;script&quot;: {<br>                &quot;source&quot;: &quot;ctx.comment = ctx.comment.substring(0,20) + &#39;\&#39;&#39; (…)&#39;\&#39;&#39;&quot;,<br>                &quot;if&quot;: &quot;ctx.containsKey(&#39;\&#39;&#39;comment&#39;\&#39;&#39;) &amp;&amp; ctx[&#39;\&#39;&#39;comment&#39;\&#39;&#39;].length() &gt; 20&quot;<br>            }<br>        }<br>    ]<br>}&#39;</pre><p>… and index a new document.</p><pre>curl -XPOST localhost:9200/my_index/_doc \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>    &quot;comment&quot;: &quot;Hello, this is a message which deserves a hair cut.&quot;<br>}&#39;</pre><h3>Extracting structured fields (parsing default NGINX log line format)</h3><p>If you are processing data that are structured in some well-defined format (but not extracted in individual fields) you can try out <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/dissect-processor.html">Dissect Processor</a>. Just describe the pattern with individual fields for extraction enclosed in curly braces with percent sign%{my_field}.</p><p>We can use this processor to parse structured field out of default NGINX log line format (combined/main) which has following structure.</p><pre>log_format main &#39;$remote_addr - $remote_user [$time_local] &#39;<br>&#39;&quot;$request&quot; $status $body_bytes_sent &#39;<br>&#39;&quot;$http_referer&quot; &quot;$http_user_agent&quot;&#39;;</pre><p>For more info on NGINX logging see docs for the logging module <a href="http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format">ngx_http_log_module</a>. We can also use the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/date-processor.html">Date Processor</a> to extract the @timestamp as the original value defaults to non-standard format.</p><p>Let&#39;s put it in new pipeline.</p><pre>curl -X PUT <a href="http://localhost:9200/_ingest/pipeline/my_simple_pipeline">localhost:9200/_ingest/pipeline/nginx_pipeline</a> \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;processors&quot;: [<br>        {<br>            &quot;dissect&quot;: {<br>                &quot;field&quot;: &quot;message&quot;,<br>                &quot;pattern&quot; : &quot;%{remote_addr} - %{remote_user} [%{time_local}] \&quot;%{request}\&quot; %{status} %{body_bytes_sent} \&quot;%{http_referer}\&quot; \&quot;%{http_user_agent}\&quot; \&quot;%{http_x_forwarded_for}\&quot;&quot;<br>            }<br>        },<br>        {<br>            &quot;date&quot;: {<br>                &quot;field&quot;: &quot;time_local&quot;,<br>                &quot;formats&quot;: [<br>                    &quot;dd/MMM/yyyy:HH:mm:ss Z&quot;<br>                ],<br>                &quot;timezone&quot;: &quot;Europe/Prague&quot;<br>            }<br>        }<br>    ]<br>}&#39;</pre><p>Now you can POST a log line in the message field and have it extracted. Note that you can override the default pipeline in our index with the new one in query string.</p><pre>curl -X POST localhost:9200/my_index/_doc?pipeline=nginx_pipeline \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;message&quot;: &quot;172.17.0.1 - - [24/Dec/2019:10:09:42 +0000] \&quot;GET / HTTP/1.1\&quot; 200 95 \&quot;-\&quot; \&quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\&quot; \&quot;-\&quot;&quot;<br>}&#39;</pre><p>Refresh your index pattern and take a look in Kibana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g3qlXO3cqqZs8n79oW-xkg.png" /></figure><p>If you want to try it in action just spin up <a href="https://hub.docker.com/_/nginx">nginx docker container</a> and find your logs in /var/log/nginx.</p><p>You can use similar processors for differently formatted contents such as <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/csv-processor.html">CSV Processor</a> (to extracts fields from csv), <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/kv-processor.html">KV Processor</a> (to parse key=value pairs) or regex-based <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/grok-processor.html">Grok Processor</a>.</p><h3>Enriching with values from another index</h3><p>Last thing we&#39;ll use is the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.x/enrich-processor.html">Enrich Processor</a> that can be used to enrich your ingested document with data from another index. Cool right!</p><p>It has three prerequisites before you can use it in your pipeline:</p><ul><li>you need to have the source index from which we will get the enrichment data</li><li>you need to define an enrich policy defining source indices, matched field and the appended fields</li><li>you need to _execute the enrich policy to create an enrich index for the policy</li></ul><p>Let’s extend the previous example and have a source index with known IP addresses (let’s just forget the fact we are now running on localhost :)) that we will check to append some data and see if the IP is not on a potential black-list.</p><p>First create the source index and one document (note: using refresh query param to be sure the index is immediately available for searching):</p><pre>curl -X POST localhost:9200/ip_source_index/_doc?refresh=wait_for \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;ip&quot;: &quot;172.17.0.1&quot;,<br>    &quot;black_listed&quot;: false,<br>    &quot;user_category&quot;: &quot;test&quot;<br>}&#39;</pre><p>Next will create the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/enrich-policy-definition.html">Enrich policy</a>. It&#39;s simple — just linking with our source index (that we created above), matching on the ip field and listing relevant fields.</p><pre>curl -X PUT localhost:9200/_enrich/policy/ip-policy \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;match&quot;: {<br>        &quot;indices&quot;: &quot;ip_source_index&quot;,<br>        &quot;match_field&quot;: &quot;ip&quot;,<br>        &quot;enrich_fields&quot;: [&quot;black_listed&quot;, &quot;user_category&quot;]<br>    }<br>}&#39;</pre><p>We need to execute it to create the enrich index.</p><pre>curl -X POST <a href="http://localhost:9200/_enrich/policy/ip-policy/_execute">localhost:9200/_enrich/policy/ip-policy/_execute</a></pre><p>Now we can finally add the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.x/enrich-processor.html">Enrich Processor</a> to our previous nginx pipeline. We need to reference the enrich policy, the field we will be matching on (remote_addr that we extracted in a previous step), target field for the enrich data and max_matches (maximum number of matched documents to include). Add following to the processors …</p><pre>{<br>    &quot;enrich&quot; : {<br>        &quot;policy_name&quot;: &quot;ip-policy&quot;,<br>        &quot;field&quot; : &quot;remote_addr&quot;,<br>        &quot;target_field&quot;: &quot;meta.ip&quot;,<br>        &quot;max_matches&quot;: &quot;1&quot;<br>    }<br>}</pre><p>Now just (re)POST the previous document (with the same nginx log line) and have the log content extracted and then enriched from our “ip info” index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_YQ33IL1Al4FYa4WuE1cw.png" /></figure><p>Nice!</p><h3>“Production” recommendations</h3><p>As a last thing I would like to point you towards additional concepts and features either of the ingest pipelines themself of useful in conjunction with them when you want to start using pipelines in your actual scenarios.</p><h4>Using along with index templates</h4><p>If you rotate your indexes (which you probably should when dealing with timeseries data, above tens of GBs in size etc.) and even more if you have these automated via <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/index-lifecycle-management.html">index lifecycle management</a> (which I tend to do) definitely recommended is to utilize the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/indices-templates.html">index templates</a>. These help to formalize configuration (settings and mappings) for all indexes created from the index template.</p><p>From the pipelines perspective you can specify in the settings:</p><ul><li><strong>index.default_pipeline </strong>which is pipeline that gets applied by default if no other is specified directly in the request (if it is the default is overriden).</li><li><strong>index.final_pipeline </strong>which runs every time after default pipeline or request pipeline.</li></ul><p>Before you include these just make sure your pipelines exist or you requests will fail.</p><h4>Pipelines simulation</h4><p>Definitely useful (when you have your pipeline in place and need to perform some changes) is to test these via <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/simulate-pipeline-api.html">_simulate API</a>. You can specify the new pipeline definition in the request body along with couple of test documents and get the results as if these were processed.</p><pre>POST /_ingest/pipeline/_simulate<br>{<br>    &quot;pipeline&quot;: {<br>        &quot;processors&quot;: [<br>            ...<br>        ]<br>    },<br>    &quot;docs&quot;: [<br>        {<br>            &quot;_index&quot;: &quot;index&quot;,<br>            &quot;_id&quot;: &quot;id&quot;,<br>            &quot;_source&quot;: {<br>                // your doc here<br>            }<br>        }<br>    ]<br>}</pre><h4>Failure handling</h4><p>Make sure you <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/handling-failure-in-pipelines.html">handle eventual failures</a> occurring during the execution of the pipeline. Do so by defining the on_failure block (consisting of some other processors) either at the level of a specific processor or of the pipeline as a whole.</p><p>Eg. pass the problematic document to a different index.</p><pre>{<br>    &quot;processors&quot;: [ … ],<br>    &quot;on_failure&quot;: [<br>        {<br>            &quot;set&quot;: {<br>                &quot;field&quot;: &quot;_index&quot;,<br>                &quot;value&quot;: &quot;failed-{{ _index }}&quot;<br>            }<br>        }<br>    ]<br>}</pre><h4>Handling of null values</h4><p>For the cases where you need a conditional execution (ie only if the field exists) make sure you handle the cases when the referenced field is missing or has an invalid value. You can do so either through ignore_missing attribute offered by some of the processors (Convert, Rename, Remove…) or in the if block.</p><pre>&quot;if&quot;: &quot;ctx.containsKey(&#39;foo&#39;) &amp;&amp; ctx[&#39;foo&#39;].containsKey(&#39;bar&#39;)&quot;</pre><h4>Reindexing</h4><p>Often when you discover ingest pipelines you already have loads of data in your existing indexes. To get this data processed by your new shiny pipeline just create a new index and use the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html">reindex API</a> to copy the data. To get the data processed either specify the pipeline in the index settings or in the reindex request body.</p><pre>POST /_reindex<br>{<br>    &quot;source&quot;: {<br>        &quot;index&quot;: &quot;source-index-*&quot;<br>    },<br>    &quot;dest&quot;: {<br>        &quot;index&quot;: &quot;destination-index&quot;,<br>        &quot;pipeline&quot;: &quot;my_pipeline&quot;<br>    }<br>}</pre><p>Note: be more cautions when <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ilm-reindexing-into-rollover.html">reindexing with ILM</a>.</p><h3>That’s it</h3><p>We went through various features of the ingest pipelines and tested them out. Hopefully you liked the intro and you can see some potential in your scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d054bf5d866" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-scratch-to-search-playing-with-your-data-elasticsearch-ingest-pipelines-6d054bf5d866">From scratch to search: playing with your data (Elasticsearch Ingest Pipelines)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From scratch to search: setup Elasticsearch under 4 minutes, load a CSV with Python and read…]]></title>
            <link>https://medium.com/data-science/from-scratch-to-search-setup-elasticsearch-under-4-minutes-load-a-csv-with-python-and-read-e31405d244f1?source=rss-6957ec4490d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e31405d244f1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Stanislav Prihoda ]]></dc:creator>
            <pubDate>Fri, 30 Aug 2019 12:41:20 GMT</pubDate>
            <atom:updated>2020-01-16T18:42:52.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fA2G5YDPGU_tc-aZ" /><figcaption>Photo by <a href="https://unsplash.com/@kymellis?utm_source=medium&amp;utm_medium=referral">Kym Ellis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>From scratch to search: setup Elasticsearch under 4 minutes, load a CSV with Python and read some more about it</h3><h4>Practical technology introduction (for data science, logging and monitoring, full-text search etc.)</h4><h3>Ready, steady, go…</h3><p>Primary aim of this article is to provide a short and simple guidance on how to initially setup your first Elasticsearch “dev” environment in order to get going quickly and start exploring/exploiting what the technology offers. The introduction will be based around the foremost APIs that Elasticsearch offers which are fundamental for getting the data in and for execution of data queries. Secondary aim is to provide links on documentation and other interesting resources to be aware of other potential operations aspects, additional cool features and various tools (generally stuff I find useful when working with Elasticsearch). I have been missing this kind of an “intro with pointers further”, so this is an attempt for anyone alike :). These links will be summed up in dedicated <strong><em>What next</em></strong> sections in each chapter.</p><p>Intended audience could be individual data analyst or web developer, eventually small teams on budget that are having relevant data use-case and have already heard of Elasticsearch. What is not intended is to provide full technical overview of the technology (clusters, nodes, shards, replicas, Lucene, inverted indexes etc.) or a deep dive on some specific topic as there are many good resources on that… some of which will be linked in the article or in the <em>What next </em>sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fKVNStNABIptz_I2" /><figcaption>Elasticsearch is… (source: Elastic <a href="https://www.youtube.com/watch?v=aLHH0eRciNE">https://www.youtube.com/watch?v=aLHH0eRciNE</a>)</figcaption></figure><h4>Elasticsearch use cases</h4><p>If you’re just wondering how Elasticsearch can be useful for your purposes, then there are generally three main areas (among other) which can be effectively supported by the <a href="https://www.elastic.co/what-is/elk-stack">Elastic Stack</a></p><ul><li><strong>“big data” analytics &amp; specific data science tasks</strong> which can revolve around having large semi-structured data (text and json objects) requiring highly available storage and fast full-text search capabilities. Interesting cases can be found for example in the <a href="https://docs.google.com/presentation/d/1Odivp6TYoeUX6sisAzE-seqwV35Fr6HPIbqGWFbI1iE/mobilepresent?slide=id.p">NLP area</a>, or when dealing with loads of GEO-based data with the need to perform <a href="https://www.elastic.co/guide/en/kibana/current/maps.html">geo-location queries and visualisations</a>. Also it can bring value if you need just a ready-made exploration/dashboarding tool for some more complex <a href="https://www.elastic.co/webinars/kibana-for-business-analytics-real-use-cases-tips-and-tricks">business analytics queries</a>.</li><li><strong>time-series processing, storage and browsing</strong> relevant for dealing with streams of time-stamped data coming in. These can include Elastic’s power area <a href="https://www.elastic.co/products/log-monitoring">log processing</a> from vast amount of running services, or their monitoring from the health and uptime perspective and also for example processing any sensor data that can be ingested into the Elasticsearch etc.</li><li><strong>full-text search of any large textual data (websites, enterprise stuff, document archives etc.)</strong> to make their content available for complex textual queries. These can (with correct setup) get returned under tens of milliseconds thus highly supporting user experience and ability to drill relevant information. Inspiration can be also found eg. in combination with <a href="https://towardsdatascience.com/making-the-mueller-report-searchable-with-ocr-and-elasticsearch-4e73e55de341">other techniques such as OCR</a>.</li></ul><h4>How we will do it</h4><p>From my perspective the easiest way to start experimenting with Elasticsearch (and many other software technologies) is via Docker and thus the examples will utilize this approach. Generally the containerisation is (already for some time) taking over also the actual production deployment/ops so this can be two-in-one benefit. Large scale example of this is presented by <a href="https://www.youtube.com/watch?v=Zl58abosobk">Uber showing their fully containerised approach</a> with hundreds of Elastic clusters. So let&#39;s do it…</p><h3>1. Setup your development environment</h3><p>I presume you are already familiar with Docker (if not… install Docker for Desktop for <a href="https://docs.docker.com/docker-for-mac/install/">Mac</a>, <a href="https://docs.docker.com/docker-for-windows/install/">Windows</a> or Linux <a href="https://docs.docker.com/install/linux/docker-ce/centos/#install-docker-ce">distributions</a>, read <a href="https://docs.docker.com/get-started/">some intro</a> stuff and you are good to go). <em>Note: examples were tested on macOS Mojave, remember there might be some Docker specifics on Linux distros or Win.</em></p><h4>Our first node</h4><p>When you have your docker environment ready just open your terminal and start Elasticsearch cluster with these commands:</p><pre>docker network create elastic-network</pre><p>This will create for us a basic communication “space” for our future containers.</p><p>Now if you want to go with just a single node deployment — just run:</p><pre>docker run --rm --name esn01 -p 9200:9200 -v esdata01:/usr/share/elasticsearch/data --network elastic-network -e &quot;node.name=esn01&quot; -e &quot;cluster.name=stanislavs-docker-cluster&quot; -e &quot;cluster.initial_master_nodes=esn01&quot; -e &quot;bootstrap.memory_lock=true&quot; --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=&quot;-Xms2g -Xmx2g&quot; docker.elastic.co/elasticsearch/elasticsearch:7.3.0</pre><p>Wait couple of seconds and in your log you should find message confirming setup success from your Elasticsearch cluster:</p><pre>{“type”: “server”, “timestamp”: “2019–08–18T13:40:18,575+0000”, “level”: “INFO”, “component”: “o.e.n.Node”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn01”, “cluster.uuid”: “ilHqkY4UQuSRYnE5hFbhBg”, “node.id”: “KKnVMTDwQR6tinaGW_8kKg”, “message”: “started” }</pre><p>Hooray… we have started our first Elasticsearch node (esn01) running in Docker container (named equally), listening on a port 9201 (docker <em>-p parameter</em>). Thanks to <em>cluster.initial_master_nodes</em> it has formed a new cluster (with name given in <em>cluster.name</em>) in the process known as <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-bootstrap-cluster.html">cluster bootstrapping</a> and immediately elected itself as the master of the cluster (what else to do when you are alone :)). Last thing worth mentioning is the <em>-v parameter</em>, which created new Docker volume esdata01 and bound it to a data directory of the running Elasticsearch — so that after restart our working data will be preserved. The rest of the parameters is more “system” related (and belong to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/system-config.html">important system settings</a>) — we disable swapping with <em>bootstrap.memory_lock</em>, increase file/process limits with <em>ulimit memlock</em> and assigned initial/max heap size with <em>ES_JAVA_OPTS</em> (ie dedicated memory so adjust to your configuration… but remember that Elasticsearch utilizes also off-heap so do not set above <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/heap-size.html">50% of available memory</a>). Licensing note: it is <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/license-settings.html">by default</a> running with a basic license but if you want to go with pure open-source flavor just add *-oss to the end of the image name.</p><h4>Other two nodes (optional)</h4><p>Now if you want to try the taste of a distributed setup add two (or more) other nodes to your cluster. It is not needed for the rest of the tutorial (running on a local machine :)) nor even actual basic operations. Nevertheless as the distribution of the processing is actually one of the core value-adding capabilities of Elasticsearch (as the indexing part is mostly taken care by <a href="https://lucene.apache.org/">Apache Lucene</a> library), it is at least good to be aware of it. So if you’re up to… here are our two other nodes (run in separate terminals):</p><pre>docker run --rm --name esn02 -p 9202:9200 -v esdata02:/usr/share/elasticsearch/data --network elastic-network -e &quot;node.name=esn02&quot; -e &quot;cluster.name=stanislavs-docker-cluster&quot; -e &quot;discovery.seed_hosts=esn01&quot; -e &quot;bootstrap.memory_lock=true&quot; --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=&quot;-Xms1g -Xmx1g&quot; docker.elastic.co/elasticsearch/elasticsearch:7.3.0</pre><pre>docker run --rm --name esn03 -p 9203:9200 -v esdata03:/usr/share/elasticsearch/data --network elastic-network -e &quot;node.name=esn03&quot; -e &quot;cluster.name=stanislavs-docker-cluster&quot; -e &quot;discovery.seed_hosts=esn01,esn02&quot; -e &quot;bootstrap.memory_lock=true&quot; --ulimit memlock=-1:-1 -e ES_JAVA_OPTS=&quot;-Xms1g -Xmx1g&quot; docker.elastic.co/elasticsearch/elasticsearch:7.3.0</pre><p>Now it starts to be more interesting as the nodes are joining our cluster. You can observe this process in logs, where you have messages about the additions (below from the master of our cluster about newly added node esn02). Generally the nodes are joining the cluster contacting other “already-present” nodes listed in <em>discovery.seed_hosts</em> parameter (to get an up-to-date info on the cluster setup) — this param belongs (along with aforementioned <em>cluster.initial_master_nodes</em>) to <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/discovery-settings.html">important discovery settings</a>. All communication between nodes in the cluster is performed directly over the Transport layer (ie without the HTTP overhead) that’s why there is the port 9300 (not the port 920x we have exposed for “outside” communication with the cluster).</p><pre>{“type”: “server”, “timestamp”: “2019–08–18T13:40:28,169+0000”, “level”: “INFO”, “component”: “o.e.c.s.ClusterApplierService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn01”, “cluster.uuid”: “ilHqkY4UQuSRYnE5hFbhBg”, “node.id”: “KKnVMTDwQR6tinaGW_8kKg”, “message”: “added {{esn02}{4xOwc-_fQDO_lwTlpPks2A}{FW-6YGVSSsmgEt3Mo_GY_Q}{172.18.0.3}{172.18.0.3:9300}{dim}{ml.machine_memory=8360488960, ml.max_open_jobs=20, xpack.installed=true},}, term: 1, version: 16, reason: Publication{term=1, version=16}” }</pre><h4>Information about our cluster</h4><p>Everything is up and running so we can check couple of things about our Elasticsearch cluster (notice that we can contact any node in our cluster as generally any node can become coordinating node to process the incoming request via <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-node.html#coordinating-node">scatter-gather approach</a>):</p><p>Basic info about the contacted node:</p><pre>curl localhost:9200</pre><p>returns:</p><pre>{<br>    &quot;name&quot; : &quot;esn01&quot;,<br>    &quot;cluster_name&quot; : &quot;stanislavs-docker-cluster&quot;,<br>    &quot;cluster_uuid&quot; : &quot;ilHqkY4UQuSRYnE5hFbhBg&quot;,<br>    &quot;version&quot; : {<br>        &quot;number&quot; : &quot;7.3.0&quot;,<br>        &quot;build_flavor&quot; : &quot;default&quot;,<br>        &quot;build_type&quot; : &quot;docker&quot;,<br>        &quot;build_hash&quot; : &quot;de777fa&quot;,<br>        &quot;build_date&quot; : &quot;2019–07–24T18:30:11.767338Z&quot;,<br>        &quot;build_snapshot&quot; : false,<br>        &quot;lucene_version&quot; : &quot;8.1.0&quot;,<br>        &quot;minimum_wire_compatibility_version&quot; : &quot;6.8.0&quot;,<br>        &quot;minimum_index_compatibility_version&quot; : &quot;6.0.0-beta1&quot;<br>    },<br>    &quot;tagline&quot; : &quot;You Know, for Search&quot;<br>}</pre><p>Basic info about the cluster status:</p><pre>curl localhost:9202/_cluster/health?pretty</pre><p>returns:</p><pre>{<br>    &quot;cluster_name&quot; : &quot;stanislavs-docker-cluster&quot;,<br>    &quot;status&quot; : &quot;green&quot;,<br>    &quot;timed_out&quot; : false,<br>    &quot;number_of_nodes&quot; : 3,<br>    &quot;number_of_data_nodes&quot; : 3,<br>    &quot;active_primary_shards&quot; : 0,<br>    &quot;active_shards&quot; : 0,<br>    &quot;relocating_shards&quot; : 0,<br>    &quot;initializing_shards&quot; : 0,<br>    &quot;unassigned_shards&quot; : 0,<br>    &quot;delayed_unassigned_shards&quot; : 0,<br>    &quot;number_of_pending_tasks&quot; : 0,<br>    &quot;number_of_in_flight_fetch&quot; : 0,<br>    &quot;task_max_waiting_in_queue_millis&quot; : 0,<br>    &quot;active_shards_percent_as_number&quot; : 100.0<br>}</pre><p>Further info about the nodes in the cluster:</p><pre>curl localhost:9203/_cat/nodes?v</pre><p>returns:</p><pre>ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name<br>172.19.0.2 26 56 3 0.01 0.16 0.17 dim * esn01<br>172.19.0.4 13 56 1 0.01 0.16 0.17 dim — esn03<br>172.19.0.3 20 56 2 0.01 0.16 0.17 dim — esn02</pre><p>Last response is probably the most interesting (as the above basically says we have an empty cluster :) . We can see all of the three nodes we have in our cluster (<em>esn01–03</em>). From node.role we can see that all <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-node.html">nodes are of the type</a> mdi — which means they are master-eligible (can be elected master if the current master “breaks down”), <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-node.html#data-node">data</a> (holds actual data ie shards and can perform CRUD/search operations) and <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/ingest.html">ingest</a> (can setup special ingest pipeline to pre-process ie transform/enrich the incoming data before actual indexing). We can also see our current master (marked with *).</p><h4>What next</h4><ul><li><strong>DEPLOYMENT</strong>: think with your devops about the best option to run in your integration/production environment — options are: standard <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/install-elasticsearch.html">local installation</a> on your servers, managed-service solution <a href="https://www.elastic.co/cloud/">Elastic Cloud</a> or <a href="https://aws.amazon.com/elasticsearch-service/">AWS Elasticsearch</a> etc. or sort of a “middle option” mentioned earlier with deploying the docker/OCI images into some containerization platform (<a href="https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-quickstart.html">Kubernetes</a>, <a href="https://www.openshift.com/">OpenShift</a>, Swarm) running again either on-prem or in the cloud</li><li><strong>CONFIGURATION</strong>: fundamental configuration resource is elasticsearch.yml file (located in <em>config</em> directory) which is present in any Elasticsearch instance — read more info on that (and other key params) in the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/important-settings.html">important settings</a></li><li><strong>SECURITY</strong>: first…! you can go with <a href="https://www.elastic.co/blog/configuring-ssl-tls-and-https-to-secure-elasticsearch-kibana-beats-and-logstash">native ES Security option</a> or with more complex setup with some Security plugin (<a href="https://search-guard.com/">SearchGuard</a>, <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/security-configuration/">Open Distro Security</a>). At least have TLS and role-based auth!</li><li><strong>CLUSTERING</strong>: so distributed much fault-tolerant … no seriously if you want to dive deeper into the clustering concepts read something about different node type ie <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-node.html">master-eligible/data/ingest/ML</a> and the dig into <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-discovery.html">discovery modules and process</a> (ie to find out why you should have <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/modules-discovery-quorums.html">three or more</a> master-eligible nodes in your cluster)</li><li><strong>SIZING</strong>: read more on <a href="https://www.elastic.co/pdf/elasticsearch-sizing-and-capacity-planning.pdf">sizing and capacity planning</a></li><li><strong>DOCKER</strong>: further info on Docker <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html">setup</a>, <a href="https://docs.docker.com/storage/volumes/">volumes</a>, <a href="https://runnable.com/docker/basic-docker-networking">networks</a> or if you are dealing with specific Elasticsearch version you can <a href="https://www.docker.elastic.co/">get matching image</a></li><li><strong>LOGGING OF ELASTICSEARCH</strong>: change <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/logging.html">logging configuration</a> (based on log4j) in specific hierarchy etc. useful when setting the thing up</li><li><strong>LICENSING</strong>: it’s good to check under which <a href="https://www.elastic.co/subscriptions">specific licensing schema</a> some specific desired feature falls (in this article I try to work with either pure oss under Apache 2.0 or <a href="https://github.com/elastic/elasticsearch/blob/master/licenses/ELASTIC-LICENSE.txt">basic-licensed</a> stuff for testing)</li><li><strong>APIs</strong>: Elasticsearch provides a good documentation of all their <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/rest-apis.html">REST APIs </a>so check it out</li><li><strong>APIs</strong>: if you liked the cat API with info on your cluster (such as I do) know that there is <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/cat.html">plenty more</a> covering nodes, shards, indices, health, segments etc. etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RbLOcv-44D7NaAzw" /><figcaption><strong>TECHNOLOGY</strong>: Read also more on the key constituting technology <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/scalability.html">components and concepts of Elasticsearch</a> (source <a href="https://www.elastic.co/pdf/elasticsearch-sizing-and-capacity-planning.pdf">elastic.co</a>)</figcaption></figure><h3>2. Get your data to Elasticsearch (CSV example)</h3><p>When you have your initial environment set up it is time to get our data to our running node(s) to be ready for searching. The basic principle of Elasticsearch is that any “unit” of our data that is put to it is called DOCUMENT. Required format of these documents is JSON. These documents are not stored individually but are grouped into specific collections that are called INDEXes. Documents in one index share similar characteristics (ie data types mappings, settings etc.), thus the index serves also as a management and API layer to the contained documents.</p><h4>Index creation</h4><p>So let’s create an index with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.1/indices-create-index.html">Create — Indices API</a> and put ie index one document to it with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/docs-index_.html">Index — Document API</a>…</p><pre>curl -X PUT \<br>  <a href="http://localhost:9200/test-csv">http://localhost:9200/test-csv</a> \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;settings&quot; : {<br>        &quot;index&quot; : {<br>            &quot;number_of_shards&quot; : 3, <br>            &quot;number_of_replicas&quot; : 2 <br>        }<br>    }<br>}&#39;</pre><p>returns:</p><pre>{“acknowledged”:true,”shards_acknowledged”:true,”index”:”test-csv”}</pre><p>Index creation… checked! We have created our first index named <em>test-csv</em> and defined an important settings of the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/scalability.html">number of shards and replicas</a>. Primary shards and shard replicas (in correct terms) are a way to split our index (ie document collection) into multiple pieces thus ensuring redundancy. Actual values depend (in a basic sense) on how many nodes we have. Number of shards (ie to how many units our index will be split into) is fixed with index creation. Number of replicas determines how many times the primary shard (ie each of our 3) will be “copied”. We have defined 2 as we want to achieve a state where on each node we have one primary shard (⅓ of our data) but also copies of other ⅔ of our data ie the full dataset. This setup ensures that if we loose one of our nodes we won’t loose any data. Hint: if you don’t want for starter to mess with these settings you don’t have to because if you attempt to index a document without an existing index — it gets created automatically (with default 1 shard and 1 replica).</p><pre>curl -X PUT \<br>  <a href="http://localhost:9203/test-csv/_doc/1?pretty">http://localhost:9203/test-csv/_doc/1?pretty</a> \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;value&quot;: &quot;first document&quot;<br>}&#39;</pre><p>returns:</p><pre>{<br>    &quot;_index&quot; : &quot;test-csv&quot;,<br>    &quot;_type&quot; : &quot;_doc&quot;,<br>    &quot;_id&quot; : &quot;1&quot;,<br>    &quot;_version&quot; : 1,<br>    &quot;result&quot; : &quot;created&quot;,<br>    &quot;_shards&quot; : {<br>        &quot;total&quot; : 3,<br>        &quot;successful&quot; : 3,<br>        &quot;failed&quot; : 0<br>    },<br>    &quot;_seq_no&quot; : 0,<br>    &quot;_primary_term&quot; : 1<br>}</pre><p>Document indexing… checked! We have indexed our first document to our test-csv index, all shards responded correctly. We have indexed a very simple json document with only one field, but you can index basically any document (from the size, depth etc perspectives) as long as it is valid JSON — but try to keep it <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/general-recommendations.html">under 100MB per doc</a> :). Now you can easily retrieve a single document by its id with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.1/docs-get.html">Get API</a>. I’ll leave that up to you.</p><h4>Using Python to load data from CSV</h4><p>Now obviously you don’t want to index your documents one by one with curl. The more when you probably already have this data somewhere in your application, database or storage drive. For these purposes there are official Elasticsearch clients for various <a href="https://www.elastic.co/guide/en/elasticsearch/client/index.html">programming languages ie Java, JS, Go, Python etc</a>. You can grab any of these based on your technology stack and use its APIs to perform indexing/deleting/updating/… actions programmatically.</p><p>But if you just have the data and want to quickly get them in you have two options… I took the <a href="https://elasticsearch-py.readthedocs.io/en/master/index.html">Python client</a> and prepared very simple CLI script that allows you to index data from given file — supporting CSV format and NDJSON format (<a href="http://ndjson.org/">newline delimited JSON</a> which is often used for logging, streaming processing etc.). Take it as a possible way how to tackle your data “problem” and write something better based on your needs :). You can browse many other methods and helpers matching the Elasticsearch APIs it offers in the <a href="https://elasticsearch-py.readthedocs.io/en/master/">client docs</a>. In any way don’t forget to <em>pip install elasticsearch</em> (to install the module) before using the script.</p><p>Code/script freely available in this repo:</p><p><a href="https://github.com/stanislavprihoda/load_csv_or_json_to_elasticsearch/blob/master/load_csv_or_json_to_elasticsearch.py">stanislavprihoda/load_csv_or_json_to_elasticsearch</a></p><p>I won’t describe the whole code contents (as it always could be written better :)), but there are two relevant parts in the code:</p><p>1.It utilizes concept of Python generator as it goes line by line through the given file and yields one preprocessed element/row for the indexing execution. This “element-wise” operation was picked on purpose to ensure memory-efficiency to be able to process even large files.</p><pre>def _csv_generator(self, es_dataset, **kwargs):<br>    with open(es_dataset.input_file) as csv_file:<br>        csv_dict_reader = csv.DictReader(csv_file)<br>        for cnt, row in enumerate(csv_dict_reader):<br>            yield self._prepare_document_for_bulk(es_dataset, row, cnt)</pre><p>2. On the other hand as the actual indexing operation is somewhat costly it utilizes the BULK API to index in multiple-document chunks (default 500 items) which is aligned with recommendations for <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/tune-for-indexing-speed.html">tuning for speed</a>). For this operation it uses one of the provided helpers (which are convenience abstractions on top of the raw api) by the python elasticsearch client — <a href="https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.streaming_bulk">elasticsearch.helpers.streaming_bulk</a>.</p><pre>for cnt, response in enumerate(streaming_bulk(self.client, generator, chunk_size)):<br>    ok, result = response</pre><p>After execution it is necessary to use the refresh API to make the documents immediately searchable.</p><pre>self.client.indices.refresh(index=es_dataset.es_index_name)</pre><p>From the data perspective there are wide options nowadays how to get some interesting data set (<a href="https://www.kaggle.com/datasets">Kaggle datasets</a>, <a href="https://registry.opendata.aws/">AWS datasets</a> or other <a href="https://skymind.com/wiki/open-datasets">curated lists</a> of open datasets), but as we will want to demonstrate also some text searching capabilities let’s test/showcase our script on something from NLP area — nice collection <a href="https://medium.com/@ODSC/20-open-datasets-for-natural-language-processing-538fbfaf8e38">can be found here</a>. We can use for example <a href="https://www.reddit.com/r/datasets/comments/1uyd0t/200000_jeopardy_questions_in_a_json_file/">Jeopardy questions dataset</a> as it is not a usual demo dataset. <em>Note: if you use this set also consider removal of whitespaces from the header to have more concise column/field names.</em></p><h4>Running</h4><p>Now we can run following command in terminal and watch the stdout logs (for testing purposes I left the DEBUG level on):</p><pre>python3 load_csv_or_json_to_elasticsearch.py _data/JEOPARDY_CSV.csv test-csv</pre><p>In the end we should receive a following message:</p><pre>2019–08–18 17:03:19,013 — load_csv_or_json_to_elasticsearch.py — INFO — Script execution FINALIZED in 44.15356087684631 seconds. Dataset from file _data/JEOPARDY_CSV.csv loaded to Elasticsearch at localhost:9200. Number of documents processed: 216929.</pre><p>The execution took <strong>44 seconds</strong> which is not that fast, but as we are running everything on a single machine it is (must be :)) acceptable. Actually quite a bit of that is the cost of the 3+2 sharding so so for test if go just with 1+0 (and single node) we are under <strong>25 seconds</strong>. It could probably be further improved by self-optimized management of the chunks sizing as recommended in tune for speed documentation (ie starting at 100 and then gradually increased until the speed plateau), so you can do it as an interesting exercise. On the other hand if we were to index the documents one by one we are up to beautiful <strong>1411 seconds</strong> :), so it seems the bulk api makes some sense.</p><p>Now we can recheck the <em>/_cat/indices?v</em> API to make sure all of our data are in place.</p><h4>What next</h4><ul><li><strong>INDEX MAPPING/SETTINGS</strong>: check the data structure of your index with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-mapping.html">Get Mapping API</a> and index settings with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html">Get Settings API</a> — there are various <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.1/index-modules.html">settings options</a>.</li><li><strong>INDEX TEMPLATING</strong>: for usecases where similar indexes get created on an ongoing basis (ie on some time periods) it is convenient to use a predefined structure for that — this is case for <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-templates.html">Index Templates</a></li><li><strong>INDEX CHANGES</strong>: you can move the data between indexes with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html">Reindex API</a> (useful when you need to make changes in sharding — which is not possible after creation), this can be used in conjunction with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html">Index Aliases</a> that allow to create a “nickname” to which we can point our queries (this layer of abstraction allows to then change the indexes behind the alias more freely)</li><li><strong>ANALYSIS</strong>: when we index or full-text search the query goes through the analysis process, read more about the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analyzer-anatomy.html">Analyzers</a> and its core building blocks <em>character filters, tokenizers, and token filters</em> or create your custom <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html">analyzer</a>.</li><li><strong>CLIENTS</strong>: official Elasticsearch clients for various <a href="https://www.elastic.co/guide/en/elasticsearch/client/index.html">programming languages ie Java, JS, Go, Python etc</a>.</li><li><strong>DATA INGESTION</strong>: usually with time-based data (such as logs, monitoring etc.) you might consider using other tools from the <a href="https://www.elastic.co/products/">Elastic Stack</a> such a <a href="https://www.elastic.co/products/beats">Beats</a> (multi-purpose lightweights data shippers) or/and <a href="https://www.elastic.co/products/logstash">Logstash</a> for more sophisticated data pre-processing before indexing to Elasticsearch</li><li><strong>MEMORY/STORAGE</strong>: if you find yourself with growing amounts of indexed data running low on disk space you might consider <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index-lifecycle-management.html">Index Lifecycle Management</a> that allows based on defined rules to change or delete indices. Or/and if you are low on memory you can consider <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/frozen-indices.html">index freezing</a> that will move various overhead data structures off the heap. Or just buy more disk space and memory :)</li><li><strong>PERFORMANCE</strong>: tune for <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/tune-for-indexing-speed.html">indexing speed</a> or efficient <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/tune-for-disk-usage.html">disk usage</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*06-GLXLGDcIE4EZ4" /><figcaption><strong>INDEX OPERATIONS &amp; ANALYSIS</strong>: read also more on how <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis.html">Analysis</a> process works — it is the core capability for fulltext searching and runs everytime we index or query our data (image source <a href="https://www.elastic.co/pdf/elasticsearch-sizing-and-capacity-planning.pdf">elastic.co</a>).</figcaption></figure><h3>3. Search</h3><p>Now that we have indexed our data we can finally search and browse through our data. Elasticsearch uses specific JSON-based language Query DSL (Domain Specific Language) to perform various complex queries across the indexed data. As there are many options in the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html">Query DSL</a> world of Elasticsearch we will just go through couple and let you try the rest.</p><h4>URI Search</h4><p>The simplest way to search in Elasticsearch though is without the Query DSL just providing the searched string as a query parameter in <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-uri-request.html">URI Search</a> which is useful for quick curl tests as Elastic itself says :). So let’s start with that and search for documents consisting the term <em>impressionism</em>.</p><pre>curl localhost:9200/test-csv/_search?q=question:impressionism</pre><p>returns:</p><pre>{<br>    &quot;took&quot;: 10,<br>    &quot;timed_out&quot;: false,<br>    &quot;_shards&quot;: {<br>        &quot;total&quot;: 3,<br>        &quot;successful&quot;: 3,<br>        &quot;skipped&quot;: 0,<br>        &quot;failed&quot;: 0<br>    },<br>    &quot;hits&quot;: {<br>        &quot;total&quot;: {<br>            &quot;value&quot;: 4,<br>            &quot;relation&quot;: &quot;eq&quot;<br>        },<br>        &quot;max_score&quot;: 13.689855,<br>        &quot;hits&quot;: [<br>(…)<br>        {<br>            &quot;_index&quot;: &quot;test-csv&quot;,<br>            &quot;_type&quot;: &quot;_doc&quot;,<br>            &quot;_id&quot;: &quot;68959&quot;,<br>            &quot;_score&quot;: 12.518969,<br>            &quot;_source&quot;: {<br>                &quot;show-number&quot;: &quot;4943&quot;,<br>                &quot;air-date&quot;: &quot;2006–02–22&quot;,<br>                &quot;round&quot;: &quot;Double Jeopardy!&quot;,<br>                &quot;category&quot;: &quot;ART &amp; ARTISTS&quot;,<br>                &quot;value&quot;: &quot;$1200&quot;,<br>                &quot;question&quot;: &quot;Impressionism got its name thanks to his painting \&quot;Impression: Sunrise\&quot;&quot;,<br>                &quot;answer&quot;: &quot;(Claude) Monet&quot;<br>            }<br>        }<br>(…)</pre><p>We can see that the query on our 216k documents took 10ms, has gone through all 3 shards successfully and 4 documents with the given term were found. The actual results are under the hits object in hits array. For each document ie hit we have received along with the actual contents in the _source field also the _score field which is a calculation of relevance</p><h4>Multi-match query</h4><p>Now let’s use the Query DSL to search across multiple fields. For this purpose we will use the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html">Multi-match query</a> that allows exactly that. As can be seen in the linked docs there are various options to play with conditions, relevance calculation and other params. Let’s keep the topic and search for <em>Claude Monet</em>. We will specify the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html">phrase as a type </a>as we want to match both, Elasticsearch would otherwise also return documents matching only one of the terms (Claude but no Monet).</p><pre>curl -X GET \<br>  <a href="http://localhost:9203/test-csv/_search">http://localhost:9203/test-csv/_search</a> \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>  &quot;query&quot;: {<br>    &quot;multi_match&quot; : {<br>      &quot;query&quot;:    &quot;Claude Monet&quot;, <br>      &quot;fields&quot;: [ &quot;category&quot;, &quot;question&quot;, &quot;answer&quot; ],<br>      &quot;type&quot;: &quot;phrase&quot; <br>    }<br>  }<br>}&#39;</pre><p>returns:</p><pre>{<br>&quot;took&quot;: 16,<br>    &quot;timed_out&quot;: false,<br>    &quot;_shards&quot;: {<br>        &quot;total&quot;: 1,<br>        &quot;successful&quot;: 1,<br>        &quot;skipped&quot;: 0,<br>        &quot;failed&quot;: 0<br>    },<br>    &quot;hits&quot;: {<br>        &quot;total&quot;: {<br>            &quot;value&quot;: 36,<br>            &quot;relation&quot;: &quot;eq&quot;<br>        },<br>        &quot;max_score&quot;: 22.763008,<br>        &quot;hits&quot;: [<br>        {<br>            &quot;_index&quot;: &quot;test-csv&quot;,<br>            &quot;_type&quot;: &quot;_doc&quot;,<br>            &quot;_id&quot;: &quot;171125&quot;,<br>            &quot;_score&quot;: 22.763008,<br>            &quot;_source&quot;: {<br>                &quot;show-number&quot;: &quot;2918&quot;,<br>                &quot;air-date&quot;: &quot;1997–04–16&quot;,<br>                &quot;round&quot;: &quot;Jeopardy!&quot;,<br>                &quot;category&quot;: &quot;CROSSWORD CLUES \&quot;I\&quot;&quot;,<br>                &quot;value&quot;: &quot;$400&quot;,<br>                &quot;question&quot;: &quot;Claude Monet or Rich Little (13)&quot;,<br>                &quot;answer&quot;: &quot;Impressionist&quot;<br>            }<br>        },<br>(…)</pre><p>We have now 36 hits and the top 10 were returned under the hits field. Btw. the first result… I wonder what would Claude say to his fellow’s impressions :).</p><h4>Boolean query</h4><p>For the third query let’s go even more complex and combine the above two searches in a way that we seek again for Claude Monet (that’s a MUST) but also we value more result matching also the term impressionism (that’s a SHOULD)… The must/should stuff might seem weird to you but as we are going to use the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/query-dsl-bool-query.html">Boolean query</a> for our search we will be using exactly these terms. Bool query is the default from so called <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/compound-queries.html">Compound queries</a> that allow combining multiple leaf queries (which are the actual queries matching some field) or other compound queries.</p><pre>curl -X GET \<br>  <a href="http://localhost:9202/test-csv/_search">http://localhost:9202/test-csv/_search</a> \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>  &quot;query&quot;: {<br>    &quot;bool&quot; : {<br>      &quot;must&quot; : {<br>        &quot;multi_match&quot; : {<br>            &quot;query&quot;:    &quot;Claude Monet&quot;, <br>            &quot;fields&quot;: [ &quot;category&quot;, &quot;question&quot;, &quot;answer&quot; ],<br>            &quot;type&quot;: &quot;phrase&quot; <br>        }<br>      },<br>      &quot;should&quot; : { <br>          &quot;match&quot; : { &quot;question&quot; : &quot;impressionism&quot; } <br>      }<br>    }<br>  }<br>}&#39;</pre><p>returns:</p><pre>{<br>    &quot;took&quot;: 6,<br>    &quot;timed_out&quot;: false,<br>    &quot;_shards&quot;: {<br>        &quot;total&quot;: 3,<br>        &quot;successful&quot;: 3,<br>        &quot;skipped&quot;: 0,<br>        &quot;failed&quot;: 0<br>    },<br>    &quot;hits&quot;: {<br>        &quot;total&quot;: {<br>            &quot;value&quot;: 36,<br>            &quot;relation&quot;: &quot;eq&quot;<br>        },<br>        &quot;max_score&quot;: 28.663502,<br>        &quot;hits&quot;: [<br>        {<br>            &quot;_index&quot;: &quot;test-csv&quot;,<br>            &quot;_type&quot;: &quot;_doc&quot;,<br>            &quot;_id&quot;: &quot;68959&quot;,<br>            &quot;_score&quot;: 28.663502,<br>            &quot;_source&quot;: {<br>                &quot;show-number&quot;: &quot;4943&quot;,<br>                &quot;air-date&quot;: &quot;2006–02–22&quot;,<br>                &quot;round&quot;: &quot;Double Jeopardy!&quot;,<br>                &quot;category&quot;: &quot;ART &amp; ARTISTS&quot;,<br>                &quot;value&quot;: &quot;$1200&quot;,<br>                &quot;question&quot;: &quot;Impressionism got its name thanks to his painting \&quot;Impression: Sunrise\&quot;&quot;,<br>                &quot;answer&quot;: &quot;(Claude) Monet&quot;<br>            }<br>        },<br>        {<br>            &quot;_index&quot;: &quot;test-csv&quot;,<br>            &quot;_type&quot;: &quot;_doc&quot;,<br>            &quot;_id&quot;: &quot;171125&quot;,<br>            &quot;_score&quot;: 22.763008,<br>            &quot;_source&quot;: {<br>                &quot;show-number&quot;: &quot;2918&quot;,<br>                &quot;air-date&quot;: &quot;1997–04–16&quot;,<br>                &quot;round&quot;: &quot;Jeopardy!&quot;,<br>                &quot;category&quot;: &quot;CROSSWORD CLUES \&quot;I\&quot;&quot;,<br>                &quot;value&quot;: &quot;$400&quot;,<br>                &quot;question&quot;: &quot;Claude Monet or Rich Little (13)&quot;,<br>                &quot;answer&quot;: &quot;Impressionist&quot;<br>            }<br>        },<br>(…)</pre><p>We can see that we have received as a top score the original result as it is the only one matching all of our terms in the exact form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p5-4XyC1NvX8nPT6" /><figcaption>Search operation in one picture (image source <a href="https://www.elastic.co/pdf/elasticsearch-sizing-and-capacity-planning.pdf">elastic.co</a>)</figcaption></figure><h4>What next</h4><ul><li><strong>QUERY DSL</strong>: check all the various options for the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/full-text-queries.html">full-text queries</a></li><li><strong>QUERY CONTEXT &amp; FILTER CONTEXT</strong>: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html">does the document match our query vs how well it matches</a></li><li><strong>LEAF QUERIES &amp; COMPOUND QUERIES</strong>: with Leaf queries look for a particular value in a particular field, such as the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/query-dsl-match-query.html">match</a>, <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/query-dsl-term-query.html">term</a> or <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/query-dsl-range-query.html">range</a> queries, on the other hand with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/compound-queries.html">Compound queries</a> you can wrap other compound or leaf queries together</li><li><strong>AGGREGATIONS</strong>: instead of working with the data on a “document-level” basis you can <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html">aggregate your results</a> to different types of aggregate outcomes such as buckets, metrices, matrixes, pipelines with wide range of options</li><li><strong>COMMON OPTIONS</strong>: see the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/common-options.html">various options</a> that can be applied to all of the REST APIs or specifically to the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-request-body.html">search query body</a></li><li><strong>PERFORMANCE</strong>: tune for the max <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/tune-for-search-speed.html">search speed</a></li><li><strong>SCORE TUNING</strong>: you can play with relevance score with <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html">Function score query</a> or Script score query (allowing custom script for score calc) or check out other <a href="https://www.elastic.co/blog/easier-relevance-tuning-elasticsearch-7-0">tunning options</a> (such as rank_feature) to make the results more relevant for your case</li><li><strong>HIGHLIGHTING &amp; SUGGESTERS</strong>: there is plentiful of other cool features such as <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html#completion-suggester">Completion suggester</a> for auto-complete/search-as-you-type functionality or <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-request-body.html#request-body-search-highlighting">Highlighting</a> for wrapping the results in html tags to emphasise where the matches are</li></ul><h3>4. Enjoy a bit of convenience with Kibana</h3><p>Up until now we have been interacting directly with our Elasticsearch cluster. In the first chapter via python client but later mostly with simple terminal cURL commands. cURL is fine for quick tests and putting things together but when you want to perform some data exploration with plotting, filtering etc. or need some tool for administration checks and updates on your cluster and indexes you might want to choose some more convenient UI-based app. Which is exactly what <a href="https://www.elastic.co/products/kibana">Kibana</a> is or as Elastic puts it <em>window to Elasticsearch</em>. Without further ado let’s add it to our setup and see what we are up to:</p><pre>docker run --rm --link esn01:elasticsearch --name kibana --network elastic-network -p 5601:5601 docker.elastic.co/kibana/kibana:7.3.0</pre><p>The <a href="https://www.elastic.co/guide/en/kibana/current/docker.html">Kibana docker</a> params are quite simple. We basically need to do two things — add Kibana to our docker network (with <em>— network</em>) and link it with our Elasticsearch cluster (eg. with <em>— link</em> pointed towards our esn01 node), we also keep the default port 5601 and pick the same version 7.3. as we are running our Elasticsearch on — <a href="https://www.elastic.co/guide/en/kibana/current/setup.html">must do for compatibility purposes</a>. <em>Note: these can also be overridden with bind-mounted </em><a href="https://www.elastic.co/guide/en/kibana/current/docker.html#bind-mount-config"><em>custom kibana.yml</em></a><em> or via </em><a href="https://www.elastic.co/guide/en/kibana/current/docker.html#environment-variable-config"><em>environment variables</em></a>. After it loads up you have your Kibana instance running at: <a href="http://localhost:5601/">http://localhost:5601</a> so don’t waste your time and check it out :). It will take you to your Home section and you can start browsing the Kibana neighbourhood.</p><h4>Management and Index Pattern</h4><p>Our goal is to start working with the data quickly so we will head straight to Management -&gt; Index Patterns and select create our first <a href="https://www.elastic.co/guide/en/kibana/current/tutorial-define-index.html">index pattern</a>. From the Kibana usage perspective the index patterns are likely the most important concept. They represent a logical structure over the Elasticsearch indexes and which tells Kibana what indexes (and related fields) to work with. Index pattern can match the name of a single index, or include a wildcard (*) to match multiple indices. So let’s create test-* index pattern (that shall match our test-csv index).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aAIw-KXvNyuPJfON" /></figure><p>In the next step we will select a timestamp field which will be later used for time-based filtering. This can be omitted by selecting I don’t want to use Time Filter but if you have any timestamp field in your data I recommend not to so that we can do time-series visualizations. Select Create and we are done. It will take you to the index pattern overview page where you have list of all your fields (which can be refreshed in top-right corner if you added some more fields). You can change the formats of the individual fields and you can also add new Scripted (but as Elastic recommends for performance purposes <em>Please familiarize yourself with </em><a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-request-script-fields.html"><em>script fields</em></a><em> and with </em><a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.3/search-aggregations.html#_values_source"><em>scripts in aggregations</em></a><em> before using scripted fields.</em>).</p><p>We can do other sorts of Elasticsearch administration/configuration stuff in the Kibana <a href="https://www.elastic.co/guide/en/kibana/7.3/management.html">Management application</a> eg. we can check out Index management section with <a href="https://www.elastic.co/guide/en/kibana/7.3/managing-indices.html">info/actions</a> on our indices (eg. freeze, delete, merge etc.) or <a href="https://www.elastic.co/guide/en/kibana/7.3/creating-index-lifecycle-policies.html">setup automatic jobs and rules</a> for Index Lifecycle Management (that will do this for us). On a last note all Kibana settings gets stored to Elasticsearch in the <em>.kibana</em> system indices so thanks to our docker volumes these will be preserved after restarts along with our other data.</p><h4>Discover</h4><p>The go-to section when you want to browse, query and filter your data is the <a href="https://www.elastic.co/guide/en/kibana/7.3/discover.html">Discover</a> application (first in the left menu). When you open it you will see our default index pattern that we have created and the individual data points.</p><p>Here you can:</p><ul><li>filter for required time range (remember our data is from 1984–2012)</li><li>filter out for required field or value (tip: use magnifier symbol next to the field or value)</li><li>use <a href="https://www.elastic.co/guide/en/kibana/7.3/kuery-query.html">Kibana Query Language</a> to perform searches on the data ie <em>category: STUPID ANSWERS</em></li><li>see basic field statistics</li><li>view your single document data and list other document in its context (ie from time perspective)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pMyAVVtU1lmA0FZf" /></figure><h4>Visualize and Dashboard</h4><p>Kibana is also useful when you’re in need to visually present your data findings or to provide interactive performance/status/metrics/KIPs overviews of the area you are dealing with. For these purposes you can create visualizations in the Kibana Visualize app and group these visualizations on rich Dashboards that can be also provided with explanatory markdowns etc. All of this is built on top of your indexed data and allows in real-time for further filtering and customizable views eg. for specific time-range.</p><p>As our showcase dataset is not really numeric in its nature we can’t really utilize all the options but let’s crate at least couple of document-counts visualizations and put them on a dashboard to have the sense of what it is about. So let’s go to the Visualize app (second on the left) and select Create new visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fgo2zjkIsTld7y4W" /></figure><p>Let’ do a count of documents (ie Questions we have in our data) grouped by year. Pick a Vertical Bar and select our test-* index pattern through which the data will be pulled. Then let’s add to Buckets and X-axis bucket with Date Histogram Aggregation, pick our air-date field and select a Yearly interval. Optionally you can drop partial buckets and in the top-right corner you should see “play arrow” button which will apply defined settings to our visualization. And… you’re done.</p><p>To put this on a Dashboard go to the Dashboard app (bellow Visualize) and Create new dashboard. In the top menu you have an Add option so use it to add a panel with your visualization. And… you’re done. Now you can try couple of these and I’m sure you can do much better than I did with my simple dashboard bellow :).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AxLntl757QmTAv3m" /></figure><h4>What next</h4><ul><li><strong>CONFIGURATION</strong>: at some point you will find the need to change other <a href="https://www.elastic.co/guide/en/kibana/current/settings.html">Kibana configurations</a> so linked is a overview of the options</li><li><strong>SECURITY</strong>: see the first <em>What next</em> section and check the linked resources as these are obviously <em>must apply</em> also for Kibana (generally there are equivalent plugins or native-capabilities also for Kibana)</li><li><strong>VISUALISATION</strong>: create a visualization in the <a href="https://www.elastic.co/guide/en/kibana/7.3/visualize.html">Visualize</a> app, put multiple visualizations together with interactive <a href="https://www.elastic.co/guide/en/kibana/7.3/dashboard.html">Dashboard</a> or share even more visually customizable reports with <a href="https://www.elastic.co/guide/en/kibana/7.3/canvas.html">Canvas</a>, if you have a GeoJSON data put the on <a href="https://www.elastic.co/guide/en/kibana/current/maps.html">Maps</a></li><li><strong>SPACES</strong>: uses <a href="https://www.elastic.co/guide/en/kibana/master/xpack-spaces.html">spaces</a> to separate out different data areas/domains etc.</li><li><strong>MONITORING</strong>: <a href="https://www.elastic.co/guide/en/elastic-stack-overview/7.3/xpack-monitoring.html">Stack Monitoring app</a> is very useful especially when dealing with higher number of instances of the stack tools (having loads of servers with Beats deployed, multiple nodes in the cluster etc.)</li><li><strong>OTHER KIBANA APPS</strong>: there are plenty depending on your stack setup eg. <a href="https://www.elastic.co/guide/en/kibana/current/xpack-uptime.html">Uptime</a> used with <a href="https://www.elastic.co/products/beats/heartbeat">Heartbeats</a> for endpoint monitoring</li><li><strong>DEV TOOLS</strong>: use <a href="https://www.elastic.co/guide/en/kibana/current/devtools-kibana.html">Dev Tools</a> when liking the Kibana UI but still want to perform some request-based stuff</li><li><strong>CSV FILE LOAD</strong>: you can perform the same CSV/NDJSON ingestion (we have done with our Python script) via still quite new Kibana tool (still with <em>Experimental</em> status) <a href="https://www.elastic.co/blog/importing-csv-and-log-data-into-elasticsearch-with-file-data-visualizer">File Data Visualizer</a> that allow index data up to 100MB — very good for quick data checks.</li><li><strong>SAMPLE DATA</strong>: if you just want to play with Kibana use <a href="https://www.elastic.co/guide/en/kibana/current/add-sample-data.html">provided sample data</a></li></ul><h3>5. Bonus — for clustering enthusiasts</h3><p>It wouldn’t be a full (distributed) picture without seeing a master election. You can play with these easily in Docker, but remember to put all back up afterwards:). We check who is the current master (eg. <em>/_cat/nodes</em> remember) and to kill it we can run:</p><pre>docker stop esn01</pre><p>This will immediately cause an exception in our cluster and initiate a master elections. Except the apparent exception (about the failed connection to the master) you can see in the logs that both nodes became candidates for the master (both are master-eligible as we already know) and execution of the elections with two candidating nodes. Everything happened under 200ms (for real life scenario also add some network overhead etc.).</p><pre>{“type”: “server”, “timestamp”: “2019–08–18T18:31:15,485+0000”, “level”: “INFO”, “component”: “o.e.c.s.ClusterApplierService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn02”, “cluster.uuid”: “w16btQPhSQ-iE96DSM6PnQ”, “node.id”: “yPAolS5gTxes0mcltF5WvA”, “message”: “master node changed {previous [{esn01}{EHEDowSVRMenU2BaVM442g}{thFwnNprQs-QwOx75KUbUg}{172.18.0.2}{172.18.0.2:9300}], current []}, term: 1, version: 5, reason: becoming candidate: onLeaderFailure” }</pre><pre>(...)</pre><pre>{“type”: “server”, “timestamp”: “2019–08–18T18:31:15,626+0000”, “level”: “INFO”, “component”: “o.e.c.s.MasterService”, “cluster.name”: “stanislavs-docker-cluster”, “node.name”: “esn03”, “cluster.uuid”: “w16btQPhSQ-iE96DSM6PnQ”, “node.id”: “rLAI506ATr6lvqw-aiKgHg”, “message”: “elected-as-master ([2] nodes joined)[{esn03}{rLAI506ATr6lvqw-aiKgHg}{pf-3B_9GTGayL4KzmGkqIQ}{172.18.0.4}{172.18.0.4:9300} elect leader, {esn02}{yPAolS5gTxes0mcltF5WvA}{kadMA9eFTO2WR4v0t4aXzQ}{172.18.0.3}{172.18.0.3:9300} elect leader, _BECOME_MASTER_TASK_, _FINISH_ELECTION_], term: 2, version: 6, reason: master node changed {previous [], current [{esn03}{rLAI506ATr6lvqw-aiKgHg}{pf-3B_9GTGayL4KzmGkqIQ}{172.18.0.4}{172.18.0.4:9300}]}” }</pre><p>Afterwards you can request the <em>/_cat/nodes?v</em> again to see who is the new boss. When you’re done you can clean things up for the fresh start with <em>docker system prune — volumes</em> which will remove unused containers, volumes, networks etc.</p><h3>Finish</h3><p>That’s it… we went through a simple “end-to-end” process with Elasticsearch starting with Docker setup, getting the data in the cluster and performing basic search queries. We then also added Kibana to our stack to have some browsing and administration comfort and useful visualisations features. From the original goals outlined in the introduction maybe the shortness wasn’t really reached :) but hopefully you gained some understanding what the technology can offer to have a basis for decision on how to eventually deploy it to your architecture. Feel free to share any additional interesting resources that can be appended to the <em>What next</em> sections lists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m039WM0IBxCXIIha" /><figcaption>Photo by <a href="https://unsplash.com/@craft_ear?utm_source=medium&amp;utm_medium=referral">Jan Tinneberg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e31405d244f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-scratch-to-search-setup-elasticsearch-under-4-minutes-load-a-csv-with-python-and-read-e31405d244f1">From scratch to search: setup Elasticsearch under 4 minutes, load a CSV with Python and read…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 2: zabezpečení Kibana (integrace LDAP)]]></title>
            <link>https://medium.com/openwise-tech-blog/elastic-ldap-kibana-184ea585c8c1?source=rss-6957ec4490d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/184ea585c8c1</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[open-distro]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[data-protection]]></category>
            <dc:creator><![CDATA[Stanislav Prihoda ]]></dc:creator>
            <pubDate>Thu, 30 May 2019 20:51:37 GMT</pubDate>
            <atom:updated>2020-01-16T18:44:12.471Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 2: zabezpečení Kibana (integrace LDAP)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T5wU_x88vUPwqpxB" /><figcaption>Photo by <a href="https://unsplash.com/@inakihxz?utm_source=medium&amp;utm_medium=referral">Iñaki del Olmo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Obecný úvod jsme si již odbyli v <a href="https://medium.com/openwise-tech-blog/elasticsearch-zabezpeceni-7fa313ccf5e1">minulém článku</a>, kde jsme se zabývali nastartováním Elasticsearch cluster a jeho základním zabezpečením. To zahrnovalo:</p><ul><li>šifrování komunikace skrze TLS,</li><li>enforce basic autentizace na všech příchozích requestech s následnou možností řízení oprávnění skrze přiřazené role v zájmu znemožnění neautorizovaných zásahů do dat,</li><li>to vše pomocí pomocí SearchGuard plugin (plus ekvivalentních možností v samostatné elasticsearch distribuci — Open Distro for Elasticsearch od AWS).</li></ul><p>Tento článek navazuje na výsledek předchozího snažení a bude doplněním k danému tématu, neboť mimo jiného ne každému musí vyhovovat komunikace s Elasticsearch čistě pomocí bash CLI a cURL 😊, které jsme využívali v minulém díle. V dnešním díle tedy do našeho setupu doplníme instanci dalšího nástroje od Elastic a to grafického vyhledávacího, vizualizačního a administračního nástroje <a href="https://www.elastic.co/products/kibana">Kibana</a>, který elastic nazývá <em>oknem do elastic stack</em>. Kibana je poměrně známý a relativně široce využívaný nástroj a je dalším ze tří pilířů tzv. ELK stack (Elasticsearch, Kibana, Logstash), který je zejména velmi populární v oblastech centralizace zpracování a prohledávání logů ale nejen tam.</p><blockquote>Pro obě varianty bude naším cílem zajistit, že každý příchozí do aplikace Kibana bude nejdříve nucen projít autentizací (skrze login) a až poté (podle přiřazené role) bude uživateli umožněno s naším Elasticsearch cluster v Kibana pracovat.</blockquote><p>Kibana toho umí ve zkratce: <a href="https://www.elastic.co/products/kibana">spoustu</a>, tentokrát se však opět (po vzoru předešlého dílu a hesla Safety first 😊) na Kibanu podíváme především pohledem zabezpečení. Dnešní článek bude defacto rozdělen do dvou částí, z nichž každá představí možný způsob řízení přístupových oprávnění. První přístup (budeme ho nazývat základní varianta) přímo naváže na předchozí setup a vzhledem k tomu, že od minule máme již nastartovaný a zabezpečený Elasticsearch cluster pomocí pluginu SearchGuard, tak nebude již příliš složité přidat nástroj Kibana jako samostatnou službu a doplnit i její zabezpečení pomocí Kibana SearchGuard plugin. Druhý způsob (dále nazýván pokročilejší varianta) naváže s Open Distro, nicméně navíc do setupu ještě přidá další komponenty a to instanci OpenLDAP jakožto autentizačního a autorizačního backendu a k němu Admin uživatelské rozhraní, které nám umožní vytvářet uživatele, role a organizační jednotky.</p><p>Pro obě varianty bude naším cílem zajistit, že každý příchozí do aplikace Kibana bude nejdříve nucen projít autentizací (skrze login) a až poté (podle přiřazené role) bude uživateli umožněno s naším Elasticsearch cluster v Kibana pracovat. Vymezení základní a pokročilejší v označení variant nereflektuje nutně míru výsledného zabezpečení (v zásadě při zachování dalších bezpečnostních pravidel a best-practices jsou technicky více či méně srovnatelné), ale spíše komplexitu výsledného organizačního nastavení a možností v procesu řízení oprávnění. První varianta z hlediska eventuálního množství zúčastněných uživatelů fituje spíše pro menší provoz, zatímco druhá by po dalším rozpracování mohla směřovat do více “enterprise” sféry.</p><h3>Základní varianta</h3><h4>Přidání instance Kibana a instalace SearchGuard plugin</h4><p>Protože se nám bude s příchodem Kibana počet provozovaných služeb zvyšovat (jinými slovy bude více než jedna 😊) využijeme rozšířených možností Docker Compose nástroje, který je určen k provozování multi-container Docker aplikací v rámci jednoho hostu, a Kibana nástroj přidáme jako samostatnou aplikační službu.</p><p>Náš <em>docker-compose.yml </em>file tedy bude vypadat následovně:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32de6d763f1be08c80252c6b84e6e876/href">https://medium.com/media/32de6d763f1be08c80252c6b84e6e876/href</a></iframe><p>Mnoho překvapení se zde neskýtá, jediné “organizačně” podstatné informace jsou, že build Kibana (i Elasticsearch) provádíme ze separátního Dockerfile viz níže a že dochází k bind mounting naší <em>kibana.yml</em> konfigurace a demo certifikátů k danému container. Náš Elasticsearch Dockerfile jsme procházeli v minulém článku, tudíž zde již v detailu rozebírat nebudem, za zmínku stojí jediná “dočasná” změna a to přidání flagu <em>-i </em>při demo konfiguraci SearchGuard, který přidá <em>searchguard.allow_default_init_sgindex: true</em> do <em>elasticsearch.yml</em>, který nám skrze auto-inicializaci usnadní práci s cluster (poznámka: rozhodně pouze pro neprodukční/demo účely).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c68ce9e7cfa65bf64a7bf03b570f3e5/href">https://medium.com/media/1c68ce9e7cfa65bf64a7bf03b570f3e5/href</a></iframe><p>V Kibana Dockerfile opět vycházíme z čistě open source verze Kibana (tzn. “oss” stejně jako u Elasticsearch) a instalujeme SearchGuard Kibana plugin z centrální Maven repository ve <a href="https://docs.search-guard.com/latest/search-guard-versions">verzi dle zvolené verze Kibana</a>. V rámci instalace přidáváme proměnnou <em>NODE_OPTIONS=” — max-old-space-size=8192&quot;</em>, abychom zvýšili paměť potřebnou pro optimalizační process Kibana, který běží po instalaci každého pluginu a který může být někdy lehce <a href="https://github.com/elastic/kibana/issues/19678">problematický</a>.</p><h4>SearchGuard a interní databáze uživatelů</h4><p>V našem případě využíváme základního zabezpečení a ověření pomocí BasicAuth a interní databáze uživatelů, které nabízí Community verze SearchGuard. V komerční verzi jsou dostupné i možnost se zapojením LDAP/AD, JWT, OpenID Connect, Kerberos apod., o tom ale až v druhé části článku. Flow, které v základním BasicAuth <a href="https://docs.search-guard.com/latest/kibana-authentication-http-basic">scénáři probíhá</a> je následující:</p><ul><li>SearchGuard kontroluje zda má uživatel aktivní session s validními credentials.</li><li>Pokud ano, tak jsou credentials přidány do veškeré komunikace (zabezpečené skrze TLS) z Kibana do Elasticsearch/SearchGuard.</li><li>SearchGuard použije tyto credentials pro autentizaci a autorizaci a přiřazení rolí a oprávnění.</li><li>V závislosti na zvoleném autentizační backendu jsou credentials kontrolovány proti interní databázi uživatelů nebo LDAP/AD.</li><li>Pokud uživatel nemá aktivní session, tak je zobrazena login stránka.</li></ul><p>Naše základní <em>kibana.yml</em> konfigurace jak pro Kibana nástroj samotný, tak z pohledu SearchGuard plugin, vypadá následovně:</p><pre>server.name: kibana<br>server.host: “0”</pre><pre>elasticsearch.hosts: <a href="https://elasticsearch:9200/">https://elasticsearch:9200</a></pre><pre>elasticsearch.username: “kibanaserver”<br>elasticsearch.password: “kibanaserver”<br>elasticsearch.ssl.verificationMode: certificate<br>elasticsearch.ssl.certificateAuthorities: “/usr/share/kibana/config/certificates/root-ca.pem”</pre><pre>searchguard.auth.type: “basicauth”<br>searchguard.basicauth.forbidden_usernames: [“kibanaserver”, “logstash”]</pre><pre>server.ssl.enabled: true<br>server.ssl.key: “/usr/share/kibana/config/certificates/esnode-key.pem”<br>server.ssl.certificate: “/usr/share/kibana/config/certificates/esnode.pem”</pre><pre>searchguard.accountinfo.enabled: true<br>searchguard.auth.anonymous_auth_enabled: false</pre><pre># not really neccessary but worth trying :)<br>searchguard.basicauth.login.brandimage: <a href="https://avatars2.githubusercontent.com/u/1540890">https://avatars2.githubusercontent.com/u/1540890</a></pre><p>Z hlediska hlavních parametrů je zde označen zabezpečený Elasticsearch cluster (<em>elasticsearch.hosts</em>), se kterým Kibana navazuje spojení, plus jsou zde uvedeny credentials technického (kýženým způsobem oprávněného) Kibana uživatele (<em>elasticsearch.username/password</em>), které jsou využívány při veškeré management komunikaci s daným Elasticsearch cluster (např. nastavování index patternů, zpracování vizualizací a dashboardů). Dále zde nastavujeme použitý typ autentizace a omezujeme uživatele z naší interní databáze (<em>searchguard.basicauth.forbidden_usernames</em>), pod kterými je možné se do Kibana přihlásit (vyjmutí aplikačních uživatelů <em>“kibanaserver”</em>, <em>“logstash”</em> pro Kibana a Logstash). V poslední části iniciujeme zabezpečení i z pohledu <a href="https://www.elastic.co/guide/en/kibana/current/configuring-tls.html">komunikace browser — Kibana</a>. Platí, že v produkčním nasazení nutno použít separátní certifikát (vystavený také pro doménu, na které Kibana poběží). Nad rámec naší základní konfigurace má Kibana sadu dalších <a href="https://www.elastic.co/guide/en/kibana/6.6/settings.html">využitelných možností</a>. Z hlediska doplňkových parametrů SearchGuard lze využít možnosti <a href="https://docs.search-guard.com/latest/kibana-authentication-anonymous">anonymních přístupů</a> (<em>searchguard.auth.anonymous_auth_enabled</em> např. je na část veřejných dat v našem cluster), <a href="https://docs.search-guard.com/latest/kibana-account-overview">přehledové obrazovky</a> s informací o přihlášeném uživateli a přiřazených rolích (<em>searchguard.accountinfo.enabled</em>), či možnosti změny <a href="https://docs.search-guard.com/latest/kibana-login-customizing">obrázku na login obrazovce</a> (<em>searchguard.basicauth.login.brandimage</em>).</p><p>Z hlediska omezení základní varianty nemůžeme pracovat např. s <a href="https://docs.search-guard.com/latest/kibana-multi-tenancy">multitenants</a> či <a href="https://docs.search-guard.com/latest/document-level-security">document-level zabezpečením</a>, nicméně to jsou vše aspekty, které lze řešit jinými způsoby a nelze je hodnotit jako přímo blokační pro nasazení.</p><p>Nyní již stačí vybuildovat naše images:</p><pre>docker-compose build</pre><p>A spustit zabezpečený Elasticsearch a Kibana:</p><pre>docker-compose up</pre><p>Při prvním otevření <a href="https://localhost:5601/">https://localhost:5601</a> (což je port na kterém nám v rámci localhost běží Kibana) se nám zobrazí login obrazovka, na které (pro test autentizace) můžeme využít některého z našich zdřívějška vytvořených demo uživatelů např. readall/readall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g2FuQFNePpPyP4XL" /></figure><h4>Vytvoření dalších uživatelů v interní databázi</h4><p>V zásadě závěrečnou informací k základní variantě je obecný postup k vytvoření dalších uživatelů v naší interní databázi, která slouží jako <a href="https://docs.search-guard.com/latest/internal-users-database">autentizační i autorizační backend</a>. Přidání uživatele má několik kroků. Proces přidání začíná v <em>sg_internal_users.yml </em>(v config adresáři SearchGuard pluginu), kde přidáme našeho nového uživatele, přiřadíme mu heslo a emitované role. K vygenerování hash passwordu v našem ukázkovém případě využijeme <a href="https://docs.search-guard.com/latest/internal-users-database#generating-hashed-passwords">hash.sh nástroj</a>, který poskytuje přímo SearchGuard. Tento nástroj vytváří salted BCrypt hash, se kterou počítá při ověřování i příslušný plugin. BCrypt je <a href="https://thehackernews.com/2014/04/securing-passwords-with-bcrypt-hashing.html">pomalá adaptivní hashovací funkce</a>, která cíleně pracuje v iterativním loopu, aby byl výsledný process pomalejší a tudíž odolnější proti slovníkovým útokům. Generování hash je jednou z nejcitlivějších částí bezpečnostního procesu, které je tak silný jako jeho nejslabší článek tzn. v produkčním nasazení je třeba zvýšené obezřetnosti a sekundárních bezpečnostních opatření.</p><p>Záznam může vypadat např. takto:</p><pre>stanislav:<br>hash: $2y$12$No8r290TijV9welgIMwoAug4al2PToCY7bpiFJiFPwUW4CXF.zUG6</pre><pre>roles:<br>- finance<br>- kibanauser</pre><p>Dále v <em>sg_roles.yml</em> <a href="https://docs.search-guard.com/latest/roles-permissions">vytvoříme roli</a> s kýženými oprávněními (v tomto případě s <a href="https://docs.search-guard.com/latest/action-groups">read akční skupinou</a> tzn. přístupem k indexům s prefixem finance_) pro přístup do <a href="https://docs.search-guard.com/latest/kibana-plugin-installation#configuring-elasticsearch-adding-kibana-users">Kibana</a>.</p><pre>financial_analyst:<br>indices:<br>‘finance_*’:<br>‘*’:<br>- READ</pre><p>A dále v <em>sg_roles_mapping.yml</em> propojíme emitované role uživatele s rolemi v searchguard.</p><pre>sg_kibana_user:<br> backendroles:<br> — kibanauser</pre><pre>financial_analyst:<br> backendroles:<br> — finance</pre><p>Nakonec platí nutnost aktualizovat zabezpečené searchguard indexy pomocí <a href="https://docs.search-guard.com/latest/sgadmin">sgadmin</a> a můžeme se přihlásit pod novým uživatelem do naší instance Kibana 😊.</p><p>Veškerý kód a konfigurace k základní variantě dostupné zde:</p><p><a href="https://github.com/stanislavprihoda/docker-elasticsearch-searchguard-6">stanislavprihoda/docker-elasticsearch-searchguard-6</a></p><h3>Pokročilejší varianta</h3><p>V druhé části se zaměříme na lehce sofistikovanější scénář, který bude bližší případům užití zejména ve větších organizacích, a to na <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/security/ldap/">integraci a ověřování proti L</a>DAP. Za tímto účelem využijeme <a href="http://www.openldap.org/">otevřené distribuce OpenLDAP</a>, která dobře poslouží našemu celkovému open source zaměření. Vzhledem k dosavadním příkladům v Docker prostředí zvolíme již publikované docker images od <a href="https://www.osixia.net/">OSIXIA</a>, kde využijeme jak samotného <a href="https://github.com/osixia/docker-openldap">OpenLDAP image</a> tak i <a href="https://github.com/osixia/docker-phpLDAPadmin">phpLDAPadmin image</a>, který poslouží jako uživatelské rozhraní k pár základním konfiguracím, které budeme provádět v naší LDAP instanci.</p><p>Z hlediska zabezpečení Elasticsearch (a dnes navíc i Kibana) využijeme tentokrát pouze <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/install/plugins/">standalone</a> Security pluginy pro oba Elastic nástroje, narozdíl od minulého článku, kde jsme využívali kompletní Open Distro distribuci (i s jádrem Elasticsearch). Standalone pluginy nám dovolí využívat z hlediska Elasticsearch a Kibana přímo distribuce od Elastic, ale přinesou kýžené bezpečnostní features. Pozadí Open Distro jsme si již představovali v minulém článku, tak jen připomenu důležitou informaci, že z pohledu Security Open Distro vychází přímo <a href="https://discuss.opendistrocommunity.dev/t/why-no-attribution-to-searchguard/131/5?u=ckressin">ze SearchGuard zdrojového kódu</a>, a tudíž i přes stále relativní čerstvost celého Open Distro konceptu lze hodnotit tyto pluginy jako validní implementační možnost. Od prvního release v březnu, a našeho úvodního článku v dubnu, AWS publikovalo několik releases Open Distro a v době psaní článku se nachází <a href="https://opendistro.github.io/for-elasticsearch-docs/#version-history">ve verzi 0.9.0</a>, která koresponduje s Elasticsearch 6.7.1.</p><h4>Instalace standalone plugin Open Distro Security a přidání instance OpenLDAP</h4><p>Množství služeb, které v našem setupu budeme provozovat, se tedy zvyšuje již na výsledné čtyři kontejnery. Příslušný <em>docker-compose.yml</em> file vypadá následovně.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d55d4fce605d0d53c20dd81809a11955/href">https://medium.com/media/d55d4fce605d0d53c20dd81809a11955/href</a></iframe><p>Z pohledu compose file se zde nenachází nic zásadně převratného. U Elasticsearch nastavujeme heap size a disablujeme swapping jakožto <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/system-config.html">důležitá doporučená nastavení</a>. Všechny služby připojujeme do stejného networku, aby byly vzájemně dostupné pro komunikaci, a pro snazší práci výsledné kontejnery i pojmenujeme. PhpLDAPadmin směřujeme na naší instanci OpenLDAP skrze proměnnou <em>PHPLDAPADMIN_LDAP_HOSTS</em> a využíváme zde i volumes pro persistenci <a href="https://lostfocus.de/2018/03/openldap-and-phpldapadmin-running-in-docker-containers/">OpenLDAP konfigurace</a> a dat. Jak bylo zmíněno výše, tak pro Elasticsearch a Kibana, nevycházíme přímo z kompletních Open Distro images, ale v rámci našeho Dockerfile k oss verzím od Elasticu doinstalujeme standalone security pluginy (<a href="https://opendistro.github.io/for-elasticsearch-docs/docs/install/plugins/">Elasticsearch</a>, <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/kibana/plugins/">Kibana</a>), které AWS distribuuje ke stažení přes cloudfront.</p><p>Např. tedy Dockerfile ke Kibana se Security pluginem vypadá následovně.</p><pre>FROM docker.elastic.co/kibana/kibana-oss:6.6.2<br>USER root<br>WORKDIR /usr/share/kibana/</pre><pre>RUN chown kibana:kibana config/kibana.yml</pre><pre># install open distro security plugin to Kibana<br>RUN bin/kibana-plugin install <a href="https://d3g5vo6xdbdb9a.cloudfront.net/downloads/kibana-plugins/opendistro-security/opendistro_security_kibana_plugin-0.8.0.0.zip">https://d3g5vo6xdbdb9a.cloudfront.net/downloads/kibana-plugins/opendistro-security/opendistro_security_kibana_plugin-0.8.0.0.zip</a></pre><pre>USER kibana</pre><pre>EXPOSE 5601</pre><p>Pozn.: v Elasticsearch Dockerfile předcházíme možným komplikacím s oprávněními u plugins instalovaných skriptem skrze <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/_other_command_line_parameters.html">force batch mode</a>.</p><p>Poslední oblastí, kterou si představíme (v našem kontextu zřejmě ta nejzajímavější) je hlavní konfigurační yaml file použitého Elasticsearch security pluginu — <em>config.yml</em>. Pozn. informaci ke struktuře config files je možné nalézt v minulém článku pro SearchGuard, přičemž pro Open Distro je z již známých důvodů ekvivalentní. V root sekci <em>opendistro_security</em> se konfigurují dvě hlavní oblasti a to autentizace (<em>authc</em>) a autorizace (<em>authz</em>), přičemž nás budou zajímat hlavně <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/security/ldap/">ty části zaměřené na integraci LDAP/AD</a>.</p><p>V sekci autentizace ponecháváme dvě možnosti — interní databázi a nově LDAP. U obou určujeme zda se využívají jak pro aplikační tak transportní vrstvu, typ http autentikačních headers (basic) a pořadí v jakém se ověřují (order). Z hlediska samotného LDAP určujeme tedy, že se skutečně jedná o daný typ autentizačního backend, v demo konfiguraci máme vypnut zabezpečený protokol komunikace tedy LDAPS (rozhodně by se nemělo objevit v produkčním využití, nicméně v tomto případě nám jde především o představení integrace než samotnou práci s certifikáty), určujeme host naší LDAP instance (název container a port), dn a credentials uživatele, pod kterým se technicky připojujeme při ověřování, omezujeme uživatelskou bázi (userbase), která je při requestech prohledávána, a určujeme samotnou query, která je exekuována při ověření (parametr {0} je při hledání nahrazen zadaným uživatelským jménem, přičemž v posledním konfiguračním parametru (username_attribute) určujeme, že stačí zadat pouze cn nikoli celé distinguished name). V sekci autorizace jsou prakticky zopakována veškerá autentizační nastavení (ve skutečnosti jsou při queries na role uživatelé znovu ověřováni) a jsou přidány ekvivalentní konfigurační parametry právě pro ověřování rolí — určujeme tedy opět bázi a query string, který je při ověřování exekuován, přičemž do pole roleOccupant je doplněn vyhledávaný uživatel. Další <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/security/ldap/#use-active-directory-and-ldap-for-authorization">config parametry</a> v našem případě primárně nevyužíváme, nicméně je možno pracovat například se víceúrovňovými (vnořenými) rolemi či naopak role pouze ve formě atributů u uživatele bez samostatné entity v ldap.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d61c4ca6fc70e7ffd9459e9838a9c5/href">https://medium.com/media/80d61c4ca6fc70e7ffd9459e9838a9c5/href</a></iframe><p>Nyní již tedy stačí vybuildovat naše images:</p><pre>docker-compose build</pre><p>A spustit všechny naše services:</p><pre>docker-compose up</pre><p>Při otevření <a href="https://localhost:5601/">https://localhost:5601/</a> se nám zobrazí již známá login obrazovka do Kibana.</p><h4>Vytvoření entit v LDAP a přihlášení do Kibana</h4><p>Nicméně naše první cesta nepovede přímo do Kibana ale do phpLDAPadminu na adresu <a href="https://localhost:6443/">https://localhost:6443</a>, kde se přihlásíme jako předdefinovaný administrátor (pod cn=admin,dc=example,dc=org) a v defaultní example organizaci vytvoříme náš zcela základní organizační setup (čistě pro showcase ověření vůči této struktuře při přihlašování do Kibana). Vytvoříme tedy (případně využijeme ze struktur v již existujícím LDAP):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*H7urvynBCty9HWm_" /></figure><ul><li>naší základní organizační jednotku (organization unit)</li><li>testovací skupinu (group)</li><li>osobního usera zařazeného v poplatné organizační jednotce</li><li>roli (přičemž v našem základním setupu je třeba dát pozor na naming, který musí odpovídat mappingu na ověřované backend role v <em>roles_mapping.yml</em>)</li><li>u role pak také nastavíme jako roleOccupant našeho uživatele</li></ul><p>Po vytvoření se již můžeme do Kibana přihlašovat pod credentials uživatelů v našem LDAP a ověřujeme, zda mají přiřazenu roli kibanauser, která nese základní oprávnění k práci s indexy.</p><p>Veškerý kód k této variantě dostupný zde:</p><p><a href="https://github.com/stanislavprihoda/docker-elasticsearch-opendistro-openldap">stanislavprihoda/docker-elasticsearch-opendistro-openldap</a></p><h3>Závěr</h3><p>V článku jsme si představili dva přístupy k ověřování přístupů koncových uživatelů do nástroje Kibana, který představuje komplexní uživatelské rozhraní k Elasticsearch cluster. Základní verze byla postavena na Community verzi SerchGuard plugin a pracovala s interní databází uživatelů, u níž jsme si představili i způsob přidávání nového uživatele. Pokročilejší varianta umožňovala, skrze standalone verzi Open Distro Security plugin, ověřovat uživatele i jejich role proti naší instanci LDAP, kterou jsme postavili na open source řešení OpenLDAP.</p><h3>Noviny ze světa Elasticsearch</h3><p>Z hlediska relevantních zpráv se hodí v kontextu našeho závěrečného bezpečnostního dílu zmínit fakt, že kromě výměny názorů/blogposts mezi Elastic a AWS očividně vyvolalo Open Distro již <a href="https://www.elastic.co/blog/security-for-elasticsearch-is-now-free">i první konkrétní reakce</a>, a Elastic se rozhodl nativní Security features v základní verzi (srovnatelné např. s Community verzí SearchGuard) zahrnout pod Basic licenci, a to od verzí 6.8.0 resp. 7.1.0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gLBgQH9YKAgOsR6sZ5R9-w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=184ea585c8c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/openwise-tech-blog/elastic-ldap-kibana-184ea585c8c1">Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 2: zabezpečení Kibana (integrace LDAP)</a> was originally published in <a href="https://medium.com/openwise-tech-blog">OpenWise Tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: zabezpečení Elasticsearch]]></title>
            <link>https://medium.com/openwise-tech-blog/elasticsearch-zabezpeceni-7fa313ccf5e1?source=rss-6957ec4490d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa313ccf5e1</guid>
            <category><![CDATA[open-distro]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[searchguard]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Stanislav Prihoda ]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 17:47:40 GMT</pubDate>
            <atom:updated>2019-08-01T12:35:23.100Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: zabezpečení Elasticsearch</h3><p>SearchGuard, Open Distro for Elasticsearch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T5aW8kBg4HcmXmnj" /><figcaption>Photo by <a href="https://unsplash.com/@daveredfern?utm_source=medium&amp;utm_medium=referral">Dave Redfern</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Úvod</h3><p>Objem dat, který se každým okamžikem celosvětově vygeneruje, nezadržitelně roste. Řada firem se předhání v odhadu přesnějšího (a ideálně co nejvyššího) <a href="https://www.seagate.com/files/www-content/our-story/trends/files/idc-seagate-dataage-whitepaper.pdf">čísla o kolik</a> se vlastně <a href="https://www.domo.com/learn/data-never-sleeps-6#/">za každou minutu</a>/den/člověka/atd. jedná, nicméně faktická (ohromující) číslovka není vlastně zcela podstatná. Co však podstatné je, že důležitější než objem surových dat, jež dokážeme vytvořit, je množství využitelných informací o našem fungování, výkonnosti, prostředí, trhu a konkurenci (atd. doplň si sám), které z daných dat dokážeme získat a to skrze jejich efektivní zpracování a vyhledávání v nich. Technologií a platforem, které v této oblasti působí je nepřeberné množství a spolu s rostoucím objemem dat je jasné, že jejich důležitost těžko bude kdy klesat.</p><h4>Elasticsearch</h4><p>Jednou ze stálic v této oblasti je nástroj <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/getting-started.html">Elasticsearch</a> postavený na technologii <a href="http://lucene.apache.org/">Apache Lucene</a>, který umožňuje zaindexování kýžených datových zdrojů ve formě tzv. JSON dokumentů a následné efektivní vyhledávání v nich. To je při <a href="https://www.elastic.co/guide/en/elasticsearch/reference/master/tune-for-search-speed.html">správném nastavení</a> skutečně, skutečně rychlé (řády milisekund) a i to nad značně velkými objemy nestrukturovaných textových dat <em>tzn. super poprvé</em>! K popularitě tohoto nástroje navíc zásadně přispívá fakt, že je ve svém jádru open-source projektem a tudíž jeho klíčových vyhledávacích a analytických funkcí je možno jednoduše využívat zdarma (dle pravidel Apache License 2.0.) <em>tzn. super podruhé</em>! “Ve svém jádru” je však podstatné vymezení, neboť business model firmy Elastic je postaven právě na všech dalších důležitých doplňkových funkcích, které jsou poskytovány a licencovány komerčně na placené subscription bázi <em>tzn. zde již je potřeba (při omezeném rozpočtu) být obezřetnější</em>.</p><h4>Safety first!</h4><p>Jednou z takových zásadních doplňkových funkcí, která je se zpřístupňováním dat a vyhledáváním v nich ruku v ruce spjata, je zajištění jejich bezpečnosti a znemožnění jejich neautorizovaných změn. Elasticsearch cluster je totiž po svém základním zprovoznění zcela “otevřený” (stejně jako jeho kód :)) a kdokoli, kdo zná jeho adresu, může kromě vyhledávání v dokumentech tyto dokumenty jakkoliv měnit, doplňovat či mazat. U některých případů užití toto nemusí být zásadní problém, nicméně u kritických či citlivých dat, která jsou využívána k business analýzám, reportingu a rozhodování nebo jsou zpřístupněna koncovým uživatelům toto určitě není zcela kýžený stav. Elastic za tímto účelem poskytuje jednu z doplňkových komerčních funkcí <a href="https://www.elastic.co/products/stack/security">Security</a> v balíku tzv. Elastic Stack Features (také známé jako X-Pack). Předmětem tohoto článku však není komerční X-Pack samotný, nicméně právě další dostupné alternativy, které poskytnou účinnou formu zabezpečení s vynaložením přiměřených zdrojů.</p><h3>Zaměření: role-based access control</h3><p>Klíčovou funkcí, na kterou jsou ukázky zaměřeny je tzv. <strong>role-based access control </strong>tedy řízení oprávnění na základě přiřazené role danému přistupujícímu uživateli (po jeho alespoň základní autentifikaci) a to právě s restriktivním cílem znemožnit plošnou možnost úpravy indexů a dokumentů v nich. Jinými slovy navodit stav kdy jeden (technický) uživatel může v našem clusteru pouze číst (read-only access) a druhý může “cokoli” (admin access).</p><p><em>Poznámka: ukázky jsou zaměřeny na co nejjednodušší možnou ilustraci základního konceptu a nesnaží se být žádným způsobem návodem k plné produkční implementaci. U té je vždy nutné zvážení řady dalších faktorů např. parametrů zpracovávaných dat či charakteristik konkrétního prostředí.</em></p><p>Ukázky jsou zprovozněny v prostředí Docker s cílem jejich co nejjednodušší reprodukce. Veškerý kód publikován zde:</p><p><a href="https://github.com/stanislavprihoda/docker-elasticsearch-searchguard-6">stanislavprihoda/docker-elasticsearch-searchguard-6</a></p><h3>Alternativa 1: SearchGuard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*zKLd2w-gdeT54pKQBlPvOA.png" /><figcaption><a href="https://search-guard.com/">search-guard.com</a></figcaption></figure><p>První zajímavou možností je využití SearchGuard pluginu do Elasticsearch od společnosti floragunn GmbH. Tento plugin nabízí již v základní verzi tzv. <a href="https://docs.search-guard.com/latest/search-guard-community-edition.html">Community Edition</a> řadu potřebných bezpečnostních funkcí např. TLS encryption (pro REST i transport layer), HTTP Basic Authentication, Role-based access control a <a href="https://search-guard.com/product/">další</a> (např. využití i pro zabezpečení uživatelského nástroje Kibana, ale o tom až příště). Navíc je daná verze licencována obdobně jako jádro Elasticsearch software samotného tedy pod Apache License 2.0. Plugin SearchGuard je pro naše účely zvolen jako reprezentant Elasticsearch pluginů třetích-stran, protože i z hlediska referencí se jedná o ověřenou záležitost. Existují však samozřejmě i další např. plugin <a href="https://readonlyrest.com/">ReadonlyREST</a>.</p><h4>Inicializace Elasticsearch clusteru a instalace SearchGuard plugin</h4><p>V Docker platformě je spuštění obou nástrojů velmi jednoduché — u Elasticsearch stačí vybrat kýženou verzi v <a href="https://www.docker.elastic.co/">publikovaných Docker images</a>. Zároveň je <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html">nabídnuta možnost</a> (z hlediska jistoty využití pouze skutečně open-source funkcí) zvolit “čisté” <em>oss </em>(<em>=</em>open-source) verze, které neobsahují doplňkové funkcionality. Dle zvolené verze Elasticsearch je třeba následně vhodně vybrat verzi SearchGuard pluginu, která má být nainstalována. Za tímto účelem je <a href="https://docs.search-guard.com/latest/search-guard-versions">vypublikována mapovací tabulka</a> mezi verzemi Elasticsearch a pluginu SearchGuard. V našem případě zvolíme Elasticsearch 6.6.2 a SearchGuard verzi 24.2.</p><p>Dockerfile tedy vypadá následovně:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4009568863bb4183f7ab5fe5e6db273/href">https://medium.com/media/c4009568863bb4183f7ab5fe5e6db273/href</a></iframe><p>Náš dockerfile je na instrukce poměrně jednoduchý. Jako base image je využit elasticsearch-oss image v kýžené verzi (poznámka: ten je postaven na base image CentOS verze 7, což je defacto pouze “převlečený” Red Hat Enterprise Linux, tzn. velmi rozšířené distribuce). Dále jsou pod root uživatelem nastavena oprávnění k relevantním elastic souborům a adresářům (pro uživatele <em>elasticsearch</em>), pod kterým se ve výsledku container spouští. Dále je nainstalován SearchGuard plugin, který je získáván z <a href="https://search.maven.org/artifact/com.floragunn/search-guard-6/6.6.2-24.2/jar">Central Maven Repository</a>. Nakonec je nakopírována naše verze skriptu <em>install_demo_configuration.sh</em> do relevantního adresáře a je spuštěn. Tento skript nastavuje po daný cluster kompletní demo konfiguraci a je dobré se na něj <a href="https://docs.search-guard.com/latest/demo-installer">blíže podívat</a>, protože poměrně dobře obecně ilustruje minimálně nutné kroky/oblasti, které je nutno řešit z hlediska nastavení zabezpečení daným pluginem (nejen v rámci demo konfigurace).</p><p>Ve shrnutí tento bash script:</p><ul><li><strong>Řeší certifikáty:</strong> přidává demo TLS certifikáty v PEM formátu do config složky Elasticsearch. <em>Poznámka: toto je primární věc, kterou lze brát jako opravdu pouze “</em><a href="https://docs.search-guard.com/latest/tls-download-certificates"><em>proof-of-concept</em></a><em>” a v potencielní produkční verzi je třeba pracovat s </em><a href="https://docs.search-guard.com/latest/tls-in-production"><em>vlastní sadou certifikátů</em></a><em>.</em></li><li><strong>Řeší searchguard konfiguraci v elasticsearch.yml: </strong>přidává potřebnou bezpečnostní konfiguraci (zejména z pohledu TLS) do hlavního configu Elasticsearch — <em>elasticsearch.yml</em>. Tu projdeme později.</li><li>Může přidat auto-initialize nastavení do <em>elasticsearch.yml</em>, které automaticky inicializuje Search Guard konfigurační index (pokud neexistuje). <em>Poznámka: v našem případě tuto možnost nevyužíváme, nicméně lze umožnit přidáním -i parametru při spouštění daného install skriptu. Výsledkem je konfigurační parametr </em><strong><em>searchguard.allow_default_init_sgindex: true</em></strong><em> v elasticsearch.yml.</em></li><li>Vygeneruje <em>sgadmin_demo.sh</em> script, který je možno použít k aplikování daného nastavení (či jeho změn) skrze příkazovou řádku. Na tento script se podíváme za chvíli.</li></ul><p>Pro spuštění už stačí pouze vybuildovat image z daného Dockerfile</p><pre>docker build . -t stanislavprihoda/elastic-sg-security</pre><p>… a spustit container na základě vytvořeného image</p><pre>docker run -p 9200:9200 stanislavprihoda/elastic-sg-security:latest</pre><h4>Konfigurace clusteru a SearchGuard plugin</h4><p>Abychom si prohlédli konfiguraci našeho clusteru, tak se stačí jednoduše připojit k výše spuštěnému containeru (přes dohledání jeho id ve výpisu běžících containers příp. můžeme v rámci docker run nastavit i — name parametr) a spustit bash shell:</p><pre>docker ps</pre><pre>docker exec -it 432a8ea6ba89 /bin/bash</pre><p>Klíčovým konfiguračním filem z hlediska Elasticsearch je <em>elasticsearch.yml</em>. Ten jak je výše zmíněno je v průběhu demo instalace SearchGuard pluginu doplněn o nutná hlavní bezpečnostní nastavení, která si blíže představíme.</p><pre>cat config/elasticsearch.yml</pre><p>Po dokončené instalaci vypadá <em>elasticsearch.yml</em> následovně</p><pre>cluster.name: “docker-cluster”<br>network.host: 0.0.0.0</pre><pre><strong>######## Start Search Guard Demo Configuration ########</strong><br># WARNING: revise all the lines below before you go into production<br>searchguard.ssl.transport.pemcert_filepath: esnode.pem<br>searchguard.ssl.transport.pemkey_filepath: esnode-key.pem<br>searchguard.ssl.transport.pemtrustedcas_filepath: root-ca.pem<br>searchguard.ssl.transport.enforce_hostname_verification: false<br>searchguard.ssl.http.enabled: true<br>searchguard.ssl.http.pemcert_filepath: esnode.pem<br>searchguard.ssl.http.pemkey_filepath: esnode-key.pem<br>searchguard.ssl.http.pemtrustedcas_filepath: root-ca.pem<br>searchguard.allow_unsafe_democertificates: true<br>searchguard.authcz.admin_dn:<br> — CN=kirk,OU=client,O=client,L=test, C=de</pre><pre>searchguard.audit.type: internal_elasticsearch<br>searchguard.enable_snapshot_restore_privilege: true<br>searchguard.check_snapshot_restore_write_privileges: true<br>searchguard.restapi.roles_enabled: [“sg_all_access”]<br>cluster.routing.allocation.disk.threshold_enabled: false<br>discovery.zen.minimum_master_nodes: 1<br>node.max_local_storage_nodes: 3</pre><pre><em>searchguard.enterprise_modules_enabled: false</em></pre><pre><strong>######## End Search Guard Demo Configuration ########</strong></pre><p>Ve výpisu vidíme dvě zásadní věci. Nastavení TLS na transport layer — tzn. pro mezi-nodovou komunikaci, která je provozována po tcp (bez http overheadu), a spuštění TLS i pro http komunikaci <em>searchguard.ssl.http.enabled: true</em>, které lze narozdíl od transport i vypnout. Z dalších nastavení je nutno také explicitně potvrdit užití demo certifikátů <em>searchguard.allow_unsafe_democertificates: true, </em>jakožto určitá bezpečností pojistka. Oproti <a href="https://github.com/floragunncom/search-guard/blob/master/tools/install_demo_configuration.sh">defaultní verzi</a> daného scriptu je do naší ukázkové verze přidáno ještě zadání jednoho nastavení a to <em>searchguard.enterprise_modules_enabled: false</em>, které zajišťuje, že jsou skutečně používány pouze <a href="https://docs.search-guard.com/latest/search-guard-community-edition">nekomerční funkce z Community Edition</a> SearchGuard pluginu.</p><p>Detailní bezpečností konfigurace SearchGuard plugin jsou umístěny v sadě .yml files v příslušné složce daného pluginu <em>~/plugins/search-guard-6/sgconfig</em>.</p><p>V našem kontextu jde především o:</p><ul><li><em>sg_config.yml</em>: hlavní config file nastavující autentizační a autorizační moduly/backendy, definující především jak sg přijmá a verfikuje credentials a permissions. V případě, že bychom uživatele chtěli autentifikovat např. oproti LDAP/AD (komerční funkcionalita), tak bychom nastavovali v tomto configu. V našem případě využijeme interní databáze uživatelů.</li><li><em>sg_internal_users.yml</em>: interní databáze uživatelů, hashed passwords a emitovaných backend rolí. Funguje jako “backend” pro autentifikaci.</li><li><em>sg_action_groups.yml</em>: formalizované sady oprávnění do skupin typu READ/MANAGE/DELETE apod.</li><li><em>sg_roles.yml</em>: definice konkrétních searchguard rolí a jim přiřazených specifických oprávnění.</li><li><em>sg_roles_mapping.yml</em>: mapování backend rolí a userů k searchguard rolím.</li></ul><p>Nejzajímavější pro naší demo aplikaci jsou informace obsažené <em>sg_internal_users.yml.</em></p><pre>cat /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/sg_internal_users.yml</pre><p>… který vypadá následovně (výňatek):</p><pre># This is the internal user database<br># The hash value is a bcrypt hash and can be generated with plugin/tools/hash.sh</pre><pre>#password is: admin<br>admin:<br> readonly: true<br> hash: $2a$12$VcCDgh2NDk07JGN0rjGbM.Ad41qVR/YFJcgHp0UGns5JDymv..TOG<br> roles:<br> — admin<br> attributes:<br> #no dots allowed in attribute names<br> attribute1: value1<br> attribute2: value2<br> attribute3: value3</pre><pre>…</pre><pre>#password is: readall<br>readall:<br> hash: $2a$12$ae4ycwzwvLtZxwZ82RmiEunBbIPiAmGZduBAjKN0TXdwQFtCwARz2<br> #password is: readall<br> roles:<br> — readall</pre><p>Ve výňatku konfigurace vidíme dva uživatele <em>admin</em> a <em>readall</em> a jim přiřazené role (tyto dva uživatele později použijeme při testu). Poznámka: pro snadnější použití demo verze jsou uvedeny v komentáři i hesla — není třeba zdůrazňovat, že v případě jakéhokoliv reálnějšího použití se toto v configu nesmí objevit! Nicméně (špatný vtip): nezapomeňte, že i největší sociální síť světa se <a href="https://krebsonsecurity.com/2019/03/facebook-stored-hundreds-of-millions-of-user-passwords-in-plain-text-for-years/">dá provozovat s volně přístupnými hesly v plaintext</a>.</p><h4>Spuštění zabezpečení clusteru skrze SearchGuard</h4><p>K iniciaci zabezpečení pomocí nainstalovaného a nakonfigurovaného SearchGuard pluginu (pokud není nakonfigurována auto-inicializace nebo došlo k nějakým změnám v nastavení searchguard) stačí spustit již dříve zmiňovaný <em>sgadmin_demo.sh</em> script z home adresáře elasticsearch.</p><pre>./sgadmin_demo.sh</pre><p>Na health-check endpointu searchguard <a href="https://localhost:9200/_searchguard/health">https://localhost:9200/_searchguard/health</a> lze následně jednoduše potvrdit, že cluster skutečně běží a SearchGuard plugin je aktivní.</p><p>Pokud ještě letmo koukneme na daný <em>sgadmin_demo.sh</em>, tak zjistíme že neobsahuje nic zásadně sofistikovaného.</p><pre>cat sgadmin_demo.sh</pre><p>… defacto především s <a href="https://docs.search-guard.com/latest/tls-download-certificates">demo admin certifikátem</a> (kirk.pem) spouští další script a to <em>sgadmin.sh</em>.</p><pre>#!/bin/bash<br>“/usr/share/elasticsearch/plugins/search-guard-6/tools/sgadmin.sh” -cd “/usr/share/elasticsearch/plugins/search-guard-6/sgconfig” -icl -key “/usr/share/elasticsearch/config/kirk-key.pem” -cert “/usr/share/elasticsearch/config/kirk.pem” -cacert “/usr/share/elasticsearch/config/root-ca.pem” -nhnv</pre><p>Zmíněný <em>sgadmin.sh</em> script je podstatně zásadnější, neboť se jedná o primární script, kterým se veškerá SearchGuard konfigurace (včetně userů, rolí, permissions atd.) indexuje do dříve vytvořeného SearchGuard indexu v Elasticsearch clusteru, ze kterého je pak načítána/využívána v exekučním prostředí. To umožňuje hot config reloading a eliminuje nutnost umísťovat konfigurační files na kterýkoli z nodů v <a href="https://docs.search-guard.com/latest/sgadmin">provozovaném clusteru</a>. Z toho vyplývá i potřeba spustit <em>sgadmin.sh</em> minimálně jednou (a následně s každou případnou změnou), abychom mohli využívat kýžených/nastavený autentizačních a autorizačních metod.</p><p>Výpis daného skriptu potvrzuje plnění sg indexů z dříve představených konfiguračních files.</p><pre>Search Guard Admin v6<br>Will connect to localhost:9300 … done<br>Elasticsearch Version: 6.6.2<br>Search Guard Version: 6.6.2–24.2<br>Connected as CN=kirk,OU=client,O=client,L=test,C=de<br>Contacting elasticsearch cluster ‘elasticsearch’ and wait for YELLOW clusterstate …<br>Clustername: docker-cluster<br>Clusterstate: GREEN<br>Number of nodes: 1<br>Number of data nodes: 1<br>searchguard index does not exists, attempt to create it … done (0-all replicas)<br>Populate config from /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/<br>Will update ‘sg/config’ with /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/sg_config.yml <br> SUCC: Configuration for ‘config’ created or updated<br>Will update ‘sg/roles’ with /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/sg_roles.yml <br> SUCC: Configuration for ‘roles’ created or updated<br>Will update ‘sg/rolesmapping’ with /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/sg_roles_mapping.yml <br> SUCC: Configuration for ‘rolesmapping’ created or updated<br>Will update ‘sg/internalusers’ with /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/sg_internal_users.yml <br> SUCC: Configuration for ‘internalusers’ created or updated<br>Will update ‘sg/actiongroups’ with /usr/share/elasticsearch/plugins/search-guard-6/sgconfig/sg_action_groups.yml <br> SUCC: Configuration for ‘actiongroups’ created or updated<br>Done with success</pre><h4>TEST TIME (indexace dokumentů)</h4><p>Nyní přichází nejzajímavější část a to zkouška provolání našeho clusteru se zapnutým zabezpečením.</p><blockquote>Yaaay!</blockquote><p>Cluster v testu provoláme celkem třikrát — poprvé zcela bez autentifikačních headers (tak jak je v základu možno s Elasticsearch pracovat, pokud nemáme zapnutou žádnou formu zabezpečení), podruhé se pokusíme zaindexovat dokument s uživatelem, který je oprávněn (na základě své role) pouze data číst, a potřetí s uživatelem, který má plná práva. Protože máme aktivované i TLS pro REST layer, tak (v rámci omezené demo konfigurace) označíme odkud má curl brát vygenerováný veřejný CA certifikát.</p><p>Request (bez autentifikačních headers):</p><pre>curl -XPUT --cacert certificates/root-ca.pem \<br> <a href="https://localhost:9200/testsecurity/_doc/1">https://localhost:9200/testsecurity/_doc/1</a> \<br> -H ‘Content-Type: application/json’ \<br> -H ‘cache-control: no-cache’ \<br> -d ‘{<br> “user” : “stanislav”,<br> “post_date” : “2019–03–24”,<br> “message” : “Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: bezpečnost”<br>}’</pre><p>Response:</p><pre>Unauthorized</pre><p>Request (s autentifikací readall uživatele) — credentials encoded v Base64:</p><pre>curl -XPUT --cacert certificates/root-ca.pem \<br> ‘https://localhost:9200/testsecurity/_doc/1?pretty=&#39; \<br> -H ‘Authorization: Basic cmVhZGFsbDpyZWFkYWxs’ \<br> -H ‘Content-Type: application/json’ \<br> -H ‘cache-control: no-cache’ \<br> -d ‘{<br> “user” : “stanislav”,<br> “post_date” : “2019–03–24”,<br> “message” : “Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: bezpečnost”<br>}’</pre><p>Response:</p><pre>{<br> “error” : {<br> “root_cause” : [<br> {<br> “type” : “security_exception”,<br> “reason” : “no permissions for [indices:data/write/index] and User [name=readall, roles=[readall], requestedTenant=null]”<br> }<br> ],<br> “type” : “security_exception”,<br> “reason” : “no permissions for [indices:data/write/index] and User [name=readall, roles=[readall], requestedTenant=null]”<br> },<br> “status” : 403<br>}</pre><p>Request (s autentifikací admin uživatele):</p><pre>curl -XPUT --cacert certificates/root-ca.pem \<br> <a href="https://localhost:9200/testsecurity/_doc/1?pretty">https://localhost:9200/testsecurity/_doc/1?pretty</a> \<br> -H ‘Authorization: Basic YWRtaW46YWRtaW4=’ \<br> -H ‘Content-Type: application/json’ \<br> -H ‘cache-control: no-cache’ \<br> -d ‘{<br> “user” : “stanislav”,<br> “post_date” : “2019–03–24”,<br> “message” : “Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: bezpečnost”<br>}’</pre><p>Response:</p><pre>{<br> “_index” : “testsecurity”,<br> “_type” : “_doc”,<br> “_id” : “1”,<br> “_version” : 1,<br> “result” : “created”,<br> “_shards” : {<br> “total” : 2,<br> “successful” : 1,<br> “failed” : 0<br> },<br> “_seq_no” : 1,<br> “_primary_term” : 1<br>}</pre><p>V poslední odpovědi vidíme úspěšně zaindexovaný dokumentu v našem testovacím indexu <em>testsecurity</em>.</p><h4>Deaktivace plugin</h4><p>Plugin se dá <a href="https://docs.search-guard.com/latest/disabling-removing-search-guard">jednoduše deaktivovat</a> jedním parametrem v <em>elasticsearch.yml</em> (upravit můžeme například ve vim editoru) a kompletním restartem clusteru (kvůli transport layer TLS který bude tímto také vypnut).</p><pre>searchguard.disabled: true</pre><p>V našem případě můžeme restartovat daný container.</p><pre>docker restart 432a8ea6ba89</pre><p>Pokud následně zkusíme zaindexovat dokument bez jakékoli autentifikace, tak vše projde bez jakýchkoliv problémů.</p><pre>curl -X PUT <a href="http://localhost:9200/testsecurity/_doc/1">http://localhost:9200/testsecurity/_doc/1</a> \<br> -H ‘Content-Type: application/json’ \<br> -H ‘cache-control: no-cache’ \<br> -d ‘{<br> “user” : “stanislav”,<br> “post_date” : “2019–03–24”,<br> “message” : “Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: bezpečnost”<br>}’</pre><h3>Alternativa 2: Open Distro for Elasticsearch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wLevIc5gWABHHo4q.jpg" /><figcaption><a href="https://aws.amazon.com/blogs/opensource/">AWS Open Source Blog</a></figcaption></figure><p>Druhá alternativa, kterou si dnes představíme, je poměrně velmi čerstvá záležitost z března letošního roku z dílny divize AWS relativně známé :) společnosti Amazon a to <a href="https://opendistro.github.io/for-elasticsearch/">Open Distro for Elasticsearch</a>. Jak už název naznačuje, tak koncepčně jde o zcela odlišnou záležitost než “pouze” security plugin do Elastic řešení, jedná se totiž o celou novou distribuci samotného Elasticsearch (spolu se sadou doplňových funkcí). Toto je možné díky právě zmíněné otevřenosti kódu Elasticsearch a vázaných software knihoven a jedná se o určitý “step-up” k již delší dobu nabízené <a href="https://aws.amazon.com/elasticsearch-service/">AWS Elasticsearch službě</a>. Reakce na tento krok (který se Amazon vysvětloval v několika <a href="https://aws.amazon.com/blogs/aws/new-open-distro-for-elasticsearch/">zprávách a blog posts</a>) na sebe pochopitelně <a href="https://www.elastic.co/blog/on-open-distros-open-source-and-building-a-company">nenechala dlouho čekat</a>. Z hlediska principů open-source komunity a rozvoje software samotného budeme doufat, že Amazon alespoň dostojí svému tvrzení, že: <em>This is not a fork; we will continue to send our contributions and patches upstream to advance these projects</em>.</p><p>Distribuce je doplněna o řadu funkcí například Alerting, SQL queries, Performance Analyzer a v neposlední řadě Security. Právě díky přítomnosti bezpečnostních funkcí dává smysl se touto alternativou v tomto článku zabývat. Spoiler alert: pokud jste pozorně četli první část článku, tak vám spousta aspektů daného řešení (rozuměj téměř všechny snad kromě instalace) začnou být velmi velmi povědomé.</p><p>Využijeme opět docker prostředí a image, který <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/install/docker/">Amazon vypublikoval</a>.</p><p>Spuštění image:</p><pre>docker run -p 9200:9200 -p 9600:9600 -e “discovery.type=single-node” amazon/opendistro-for-elasticsearch:0.7.0</pre><p>Opět se rovnou připojíme k danému containeru:</p><pre>docker exec -it f61520fefc92 /bin/bash</pre><p>A pokud pak vylistujeme příslušný <em>elasticsearch</em> adresář:</p><pre>[root@f61520fefc92 elasticsearch]# ls</pre><p>tak uvidíme jeden povědomý script file…</p><pre>LICENSE.txt NOTICE.txt README.textile bin config data lib logs modules plugins <strong><em>securityadmin_demo.sh</em></strong></pre><p>Script <em>securityadmin_demo.sh</em> již dobře známe z představení pluginu SearchGuard. Zkusíme se tedy podívat do adresáře <em>plugins</em>.</p><pre>opendistro_alerting opendistro_performance_analyzer opendistro_security opendistro_sql</pre><p>Zde vidíme dříve zmíněné moduly, které byly doplněny do Open Distro for Elasticsearch a jsou pojmenovány prefixem <em>opendistro_</em>. Když se však podíváme do adresáře security plugin a jeho konfigurace</p><pre>[root@f61520fefc92 plugins]# ls opendistro_security/securityconfig/</pre><p>… tak vidíme známou sadu config files (akorát bez <em>sg_</em> prefixu)</p><pre>action_groups.yml config.yml elasticsearch.yml.example internal_users.yml roles.yml roles_mapping.yml</pre><p>Zmínku, že bylo v Open Distro for Elasticsearch využito kódové báze SearchGuard je možné nalézt pouze v <a href="https://github.com/opendistro-for-elasticsearch/security/blob/master/NOTICE.txt">licenčním NOTICE dokumentu</a>, kde je uveden copyright pro výrobce daného plugin <em>Copyright 2015–2017 floragunn GmbH</em>. Vývojářská firma <em>floragunn</em> potvrdila využítí a jeho legitimitu v <a href="https://discuss.opendistrocommunity.dev/t/why-no-attribution-to-searchguard/131/5?u=ckressin">krátkém vyjádření na svém community fóru</a>.</p><p>Závěr pro nás? Veškerá diskutovaná nastavení SearchGuard jsou plně ekvivalentní i pro <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/security/">nastavení</a> Open Distro for Elasticsearch.</p><h3>Závěr</h3><p>Jak bylo ilustrováno, tak SearchGuard je efektivním a ozkoušeným standardem v oblasti zabezpečení Elasticsearch clusterů, což částečně “dokazuje” i využití jeho kódu Amazonem v Open Distro for Elasticsearch. Tento plugin nabízí poměrně široké možnosti nastavení a zabezpečení a to i ve volně dostupné Community Edition. Osobně by v tuto chvíli bylo doporučení (z hlediska funkcionalit základního zabezpečení představených výše) zatím používat spíše distribuce přímo od <em>Elastic</em> a <em>floragunn</em> vzhledem k přímému přístupu k aktualizacím a široké aktivní komunitě. Uvidíme až časem jaká bude kontribuce Amazonu v dané oblasti.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YBO5nBNSETLF712bjK3WPA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa313ccf5e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/openwise-tech-blog/elasticsearch-zabezpeceni-7fa313ccf5e1">Nesnesitelná lehkost vyhledávání (ve vašich datech) — díl 1: zabezpečení Elasticsearch</a> was originally published in <a href="https://medium.com/openwise-tech-blog">OpenWise Tech blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>