<?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 Brilian Firdaus on Medium]]></title>
        <description><![CDATA[Stories by Brilian Firdaus on Medium]]></description>
        <link>https://medium.com/@brilianfird?source=rss-c5d888ffc5e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*P03frwfXXRkSLnHt3M-L0g.jpeg</url>
            <title>Stories by Brilian Firdaus on Medium</title>
            <link>https://medium.com/@brilianfird?source=rss-c5d888ffc5e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:16:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brilianfird/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[Incident Management Platform in Blibli.com]]></title>
            <link>https://medium.com/bliblidotcom-techblog/incident-management-platform-in-blibli-com-bf213bfc5bbb?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf213bfc5bbb</guid>
            <category><![CDATA[alert-management]]></category>
            <category><![CDATA[root-cause-analysis]]></category>
            <category><![CDATA[disaster-response]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[risk-management]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 04:37:22 GMT</pubDate>
            <atom:updated>2024-02-13T06:35:00.197Z</atom:updated>
            <content:encoded><![CDATA[<h4>Streamlining the Incident Management Flow in Blibli.com</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*QlfD1mbGgxXNt2if" /></figure><p>An incident is an unplanned event affecting the system’s customer experience. This could be system failure, errors, slow performance, security breaches, etc. It’s something that will always occur, no matter how much you try to prevent it.</p><p>Once an incident is identified, the service owners need to analyze the incident and determine the root cause. This involves gathering data, conducting investigations, and collaborating with various stakeholders such as developers, DevOps, and DBA. Once the root cause is identified, the team can resolve the incident as quickly as possible.</p><p>Effective incident management involves a well-defined process, clear communication channels, and automated incident management tools. This ensures that incidents are resolved promptly and efficiently, minimizing the impact on the business and its customers.</p><p>In this article, we&#39;ll share how we built the incident management system in <a href="http://blibli.com/">Blibli.com</a> to improve the incident handling process. What we will explore are:</p><ol><li><strong>How things were before the Incident Management platform</strong>: We&#39;ll explore how we managed our incident before introducing the Incident Management platform.</li><li><strong>Why do we need the platform for?</strong>: There are reasons why we decided to create the Incident Management platform. In this section, we&#39;ll take a look at the problems we faced and how introducing the platform will help the engineering process.</li><li><strong>How the platform is implemented:</strong> Now that we know what we want to build, let&#39;s check out how we built it.</li></ol><h3>Our Incident Handling Process Before The Incident Management Platform</h3><p>At <a href="http://blibli.com/">Blibli.com</a>, we already have an incident-handling process before introducing the incident management platform. We connect our monitoring tools, Datadog and Prometheus, to the PagerDuty as our alerting tool.</p><p>The process of handling an incident is different between teams, but in general, what will happen is in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*__6_m7Y9YQOpadEp.png" /><figcaption>Incident Handling Flow</figcaption></figure><p>As you can see, our process requires a lot of juggling between tools. We used:</p><ol><li>PagerDuty as our alerting tool</li><li>Datadog/Prometheus as our system monitoring tool</li><li>DBA/DevOps tooling to check DBA/DevOps on Standby</li><li>Microsoft Teams for coordination</li><li>Confluence to create the postmortem and RCA of the incident</li><li>JIRA to create and track action plans from the incident</li><li>And lastly, email to send out the postmortem and RCA of the incident</li></ol><h3>Determining What To Build</h3><p>When creating the incident management platform, we identified three areas where we could improve our processes:</p><ol><li><strong>Preventing incidents:</strong> The most important step in reducing the number of incidents is to prevent them from happening in the first place. There are various ways to achieve this, such as implementing good CI/CD practices and using pull requests, which we already have in <a href="http://blibli.com/">Blibli.com</a>. To further improve, we have decided to increase transparency around incidents so that people can be more aware and better understand them.</li><li><strong>Filtering incidents:</strong> We currently have multiple alerts set up for our services. However, not all of them are urgent and require immediate attention. For example, a service may have a high error rate because the downstream service it calls is down. In this case, the root cause should be identified in the downstream service instead. By filtering and categorizing incidents, we can reduce the overwhelmed feeling for on-call engineers.</li><li><strong>Faster Incident Handling</strong>: Incidents will always happen, no matter how much we try to prevent them. In these cases, we want to help the engineers to focus and resolve the incidents quickly.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*eGtKJg6b6rUjFPKD.png" /><figcaption>Incident Funnel</figcaption></figure><p>Improving each area will create a funnel to determine which incidents to handle. Ultimately, this will also help with faster incident handling.</p><p><strong>Preventing Incidents</strong></p><p>When an incident occurs, the incident commander will analyze and resolve the incident as fast as possible. Another important step after the incident is resolved is to let the incident known to other people. So, when the same incident occurs, other teams can resolve the incident quicker.</p><p>To improve incident prevention, we centralized our incident data, which was previously scattered throughout the Confluence. In addition, we also added alerts and reporting. In conclusion, we planned to:</p><ol><li><strong>Centralized Incident Data:</strong> We wanted to store all the incident data and postmortems in the incident management system to find them quicker.</li><li><strong>Email Alerting</strong>: One improvement we planned for the incident management platform is to add email alerts whenever an incident is triggered. While PagerDuty already has this feature, we decided to add it to the incident management system as well to ensure that users can easily access the URL of the incident in the new UI.</li><li><strong>Email Reporting</strong>: One of our goals is to increase transparency so everyone knows what incidents are happening and how they are resolved. To achieve this, we plan to send weekly reports containing information on incidents from the previous week and monthly reports providing a high-level overview of how many incidents are occurring per team. Additionally, we plan to send an email every time an incident is closed containing the root cause analysis and steps for resolution.</li></ol><p><strong>Filtering The Incidents</strong></p><p>To reduce the number of alerts that engineers receive and minimize noise, we wanted to filter incidents and distinguish between those that require immediate attention and those that can be ignored. To achieve this, we focused on three areas of improvement:</p><ol><li><strong>Determine Incident Level</strong>: To improve incident handling, we mapped incident names to levels so that only high-priority incidents that require urgent attention and postmortems from engineers are addressed promptly.</li><li><strong>Duplicate Incident Detection</strong>: To prevent multiple alerts in the incident management system, we added a feature to detect duplicate incidents and link them to their parent incident. This helps to reduce the number of alerts and makes the system more efficient.</li><li><strong>Cascading Incident Detection</strong>: We added cascading incident detection to the IM system to help the incident commander get more context about an incident happening in their service. This feature helps identify when an incident in one service causes another in a different service.</li></ol><p><strong>Faster Incident Handling</strong></p><p>When an incident occurs, we want to assist the engineers in resolving it quickly. We aim to have the engineers focus solely on the incident to achieve this. Therefore, we intend to create automation to reduce the required context switching. For this category, we have the following checklist:</p><ol><li><strong>Automated creation of MS Teams chat rooms:</strong> We will automatically create a chat room that includes the service owner, DevOps on standby, DBA on standby, and stakeholders.</li><li><strong>Automatic Postmortem Page Creation</strong>: The system will automatically create a postmortem page whenever an incident is declared. The postmortem page will include an RCA template to streamline our RCA process.</li><li><strong>Automatic JIRA task creation</strong>: The system will automatically create a JIRA task for completing the postmortem. Additionally, when creating action plans related to the incident, the system generates a JIRA task. This will make it easier to track the incident via JIRA.</li></ol><h3>How We Implemented The Incident Management Platform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*kCuUPIV9tzTFVlIB6NbNaA.png" /><figcaption>Incident Management Simplified Architecture Diagram</figcaption></figure><p>We have two ways of creating an incident in the incident management system:</p><ol><li><strong>Automated incident detection</strong>: Since we’re already using PagerDuty as our alerting tool, we decided to leverage it by adding a <em>webhook</em> call from PagerDuty to the incident management system. This way, every alert we’ve set in Datadog and Prometheus will be forwarded to the incident management system and detected as an incident.</li><li><strong>Manual incident creation</strong>: If there is an incident that’s not detected by Datadog/Prometheus, for example, a security incident or an incident that the alert has not been set up, the PIC can create the incident manually in the incident management system through Incident Management UI</li></ol><p>We also integrated our system with external services like Microsoft Teams API, JIRA, email services, and our internal tooling to automate things.</p><h4>Incident Flow</h4><p>Let&#39;s now focus on the incident we received from PagerDuty. We&#39;ve created a graphic to help understand how the incident flows through our newly built incident management system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kjmu2Y64to1WBOOP.png" /><figcaption>Life of an Incident</figcaption></figure><p><strong>Incident Priority</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*2fwLm9lSza24RoBtzQk9iQ.png" /><figcaption>Incident Priority</figcaption></figure><p>Incident priority is determined by how urgent we think the incident needs to be handled and whether it requires a postmortem. We have decided on three levels that require a postmortem: when a service is down, has a high error percentage, or has a high response time.</p><p>The system automatically creates a Teams chat room when a service is down. This chat room will contain the service owner, stakeholders, DBA, and DevOps. We have decided to create a chat room only for service downtime, as it is the most urgent incident to resolve. We do not want to create unnecessary chat rooms and spam teams with sensitive alerts.</p><p><strong>Resolving Incident Status</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QKrdnYA6D1gUKkvm.png" /><figcaption>Incident Status Mapping</figcaption></figure><p>To determine the current status of the incident, we needed to map the PagerDuty status to our own. Since PagerDuty has many incident statuses, we decided to simplify it to only three to make things easier:</p><ol><li><strong>Open</strong>: The incident is still ongoing and has not been resolved yet.</li><li><strong>Resolved</strong>: The incident has been resolved, but the postmortem and RCA have not been written yet.</li><li><strong>Closed</strong>: The incident is closed, and no further action is needed.</li></ol><p><strong>Cascading and Duplicate Incident Detection</strong></p><p>To reduce the number of alerts and postmortem requests sent to engineers, we added a feature that detects cascading and duplicate incidents in the system. We used Datadog to store a map of our service dependencies (which services call other services) and called it to determine whether a service is related to another or not. This was necessary because only related services can have cascading incidents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArhyV0N1YqD9rbROrtAstw.png" /><figcaption>Cascading and Duplicate Incident Detection Flowchart</figcaption></figure><h3>The Result</h3><p>It always takes some time to change department-wide process. However, bit by bit, the team at <a href="http://blibli.com/">Blibli.com</a> started adapting to the platform. The platform also garnered interest from the data team, who decided to create a dashboard to track the financial impact of each incident. Additionally, we started using incidents as an engineering metric, making the availability and reliability of the services a priority for each team.</p><p>Here, we will showcase some of the features of Incident Management:</p><p><strong>Incident Summary</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9bW_80J5nAbPkncJ-O-qw.png" /><figcaption>Incident Summary Per Squad</figcaption></figure><p><strong>Incident RCA Template</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W1eEBWsoE2_Ob8GA" /><figcaption>Incident RCA Page</figcaption></figure><p><strong>Create Incident Page</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5CcXyL3amZawAg_Q" /><figcaption>Manual Incident Creation Page</figcaption></figure><p><strong>Incident Impact Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VmanHjz8VTbcdVuRq8eb-A.png" /><figcaption>Incident Impact Dashboard (Masked)</figcaption></figure><p><strong>Squad Incident Trend Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hP_brSdcITJrQSkLzxI6xg.png" /><figcaption>Incident Trend Dashboard (Masked)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf213bfc5bbb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bliblidotcom-techblog/incident-management-platform-in-blibli-com-bf213bfc5bbb">Incident Management Platform in Blibli.com</a> was originally published in <a href="https://medium.com/bliblidotcom-techblog">Blibli.com 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[How To Implement JSON Web Token (JWT) in Java Spring Boot]]></title>
            <link>https://medium.com/better-programming/how-to-implement-json-web-token-jwt-in-java-spring-boot-943084ad1592?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/943084ad1592</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 19:48:23 GMT</pubDate>
            <atom:updated>2022-08-04T19:48:23.007Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief guide to this helpful feature</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*l2iewA5vBhS7YFso" /><figcaption>image from Pixabay</figcaption></figure><p>JSON Web Token or JWT has been famous as a way to communicate securely between services. There are two forms of JWT: JWS and JWE. The difference between them is that JWS’s payload is not encrypted while JWE is.</p><p>This article will explore the implementation of the JWT in Java Spring Boot. If you want to learn more about the JWT itself, you can visit my other article <a href="https://codecurated.com/blog/introduction-to-jwt-jws-jwe-jwa-jwk/">here</a>.</p><p>The code in this article is hosted on the following GitHub repository: <a href="https://github.com/brilianfird/jwt-demo">https://github.com/brilianfird/jwt-demo</a>.</p><h3>Library</h3><p>For this article, we will use the jose4j library. jose4j is one of the popular JWT libraries in Java and has a full feature. If you want to check out other libraries (whether it&#39;s for Java or not), <a href="https://jwt.io/libraries">jwt.io</a> has compiled a list of them.</p><pre>&lt;dependency&gt;  <br>    &lt;groupId&gt;org.bitbucket.b_c&lt;/groupId&gt;  <br>    &lt;artifactId&gt;jose4j&lt;/artifactId&gt;  <br>    &lt;version&gt;0.7.12&lt;/version&gt;  <br>&lt;/dependency&gt;</pre><h3>Implementing JWS in Java</h3><p>JSON Web Signature (JWS) consists of three parts:</p><ul><li>JOSE Header</li><li>Payload</li><li>Signature</li></ul><p>Let’s see an example of the JOSE header:</p><pre>{<br>	alg:&quot;HS264&quot;<br>}</pre><p>JOSE header store the metadata about how to handle the JWS.<br>alg stores information about which signing algorithm the JWT uses.</p><p>Next, let’s check the payload:</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Brilian Firdaus&quot;,<br>  &quot;iat&quot;: 1651422365<br>}</pre><p>JSON payload stores the data that we want to transmit to the client. It also stores some JWT claims for information purposes that we can verify.</p><p>In the example above, we have three fields registered as JWT claims.</p><ul><li>sub indicates the user&#39;s unique id</li><li>name indicates the name of the user</li><li>iat indicates when we created the JWT in an epoch</li></ul><p>The last part is the signature, which is the one that makes JWS secure. Usually, the signature of the JWS will be in the form of bytes. Let’s see an example of a Base64 Encoded signature:</p><pre>qsg3HKPxM96PeeXl-sMrao00yOh1T0yQfZa-BsrtjHI</pre><p>Now, if we see the three parts above, you might wonder how to transfer those three parts seamlessly to the consumer. The answer is with compact serialization. Using compact serialization, we can easily share the JWS with the consumer because the JWS will become one long string.</p><pre>Base64.encode(JOSE Header) + &quot;.&quot; + Base64.encode(Payload) + &quot;.&quot; + Base64.encode(signature)</pre><p>The result will be:</p><pre>eyJhbGciOiJIUzI1NiIsImtpZCI6IjIwMjItMDUtMDEifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJyaWxpYW4gRmlyZGF1cyIsImlhdCI6MTY1MTQyMjM2NX0.qsg3HKPxM96PeeXl-sMrao00yOh1T0yQfZa-BsrtjHI</pre><p>The compact serialization part is also mandatory in the JWT specification. So for a JWS to be considered a JWT, we must do a compact serialization.</p><h3>Unprotected</h3><p>The first type of JWS we will explore is an unprotected JWS. People rarely use this type of JWS (basically just a regular JSON), but let’s explore this first to understand the base of the implementation.</p><p>Let’s start by creating the header. Unlike the previous example where we used the HS256 algorithm, now we will use no algorithm.</p><h3><strong>Producing Unprotected JWS</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e03684566d376ce14d61fd01944ceec/href">https://medium.com/media/1e03684566d376ce14d61fd01944ceec/href</a></iframe><p>Let’s see what we did in the code:</p><ul><li>We set a bunch of claims (sub, iat, exp, iss, name, email, email_verified)</li><li>We set the signing algorithm to NONE and the algorithm constraint to NO_CONSTRAINT because jose4j will throw an exception because the algorithm lack security</li><li>We packaged JWS in the compact serialization, which will produce one string containing the JWS. The result is a JWT complied String.</li></ul><p>Let’s see what output we get by calling the jws.getCompactSerialization():</p><pre>eyJhbGciOiJub25lIn0.eyJzdWIiOiI3NTYwNzU1ZS1mNDVkLTRlYmItYTA5OC1iODk3MWMwMmViZWYiLCJpYXQiOjE2NTI1NTYyNjYsImV4cCI6MTY1MzE2MTA2NiwiaXNzIjoiaHR0cHM6Ly9jb2RlY3VyYXRlZC5jb20iLCJuYW1lIjoiQnJpbGlhbiBGaXJkYXVzIiwiZW1haWwiOiJicmlsaWFuZmlyZEBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZX0.</pre><p>If we try to decode it, we’ll get the JWS with fields that we set before:</p><pre>{<br>  &quot;header&quot;: {<br>    &quot;alg&quot;: &quot;none&quot;<br>  },<br>  &quot;payload&quot;: {<br>    &quot;sub&quot;: &quot;7560755e-f45d-4ebb-a098-b8971c02ebef&quot;,<br>    &quot;iat&quot;: 1652556266,<br>    &quot;exp&quot;: 1653161066,<br>    &quot;iss&quot;: &quot;https://codecurated.com&quot;,<br>    &quot;name&quot;: &quot;Brilian Firdaus&quot;,<br>    &quot;email&quot;: &quot;brilianfird@gmail.com&quot;,<br>    &quot;email_verified&quot;: true<br>  }<br>}</pre><p>We’ve successfully created a JWT with Java’s jose4j library! Now, let&#39;s proceed to the JWT-consuming process.</p><p>To consume the JWT, we can use the JwtConsumer class in the jose4j library. Let&#39;s see an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/998387b7de6fa5dd82ba369cd5531c38/href">https://medium.com/media/998387b7de6fa5dd82ba369cd5531c38/href</a></iframe><p>By using JwtConsumer, we can easily make rules about what to validate when processing incoming JWT. It also provides an easy way to get the JWS Object and the claims by using .getJoseObjects() and getJwtClaims(), respectively.</p><p>Now that we know how to produce and consume JWT without a signing algorithm, it will be much easier to understand the one with it. The difference is that we need to set the algorithm and create a key(s) to generate/validate the JWT.</p><h3>HMAC SHA-256</h3><p>HMAC SHA-256(HS256) is a MAC function with a symmetric key. We will need to generate at least 32 bytes for its secret key and feed it to the HmacKey class in the jose4j library to ensure security.</p><p>We’ll use the SecureRandom library in Java to ensure the key randomity.</p><pre>byte[] key = new byte[32];  <br>  <br>SecureRandom secureRandom = new SecureRandom();  <br>secureRandom.nextBytes(key);<br><br>HmacKey hmacKey = new HmacKey(key);</pre><p>The secret key should be considered a credential. Hence it should be stored in a secure environment. For recommendation, you can store it as an environment variable or in [Vault](https://www.vaultproject.io/).</p><p>Let’s see how to create and consume the JWT signed with HS256:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a573e515ac4aeb8d36a825827aeb8e33/href">https://medium.com/media/a573e515ac4aeb8d36a825827aeb8e33/href</a></iframe><p>There isn’t much difference in the code compared to creating a JWS without a signing algorithm. We first made the key using SecureRandom and HmacKey classes. Since HS256 uses a symmetric key, we only need one key that we will use to sign and verify the JWT.</p><p>We also set the algorithm header value to HS256 by using jws.setAlgorithmheaderValue(AlgorithmIdentifiers.HMAC_SHA256 and the key with jws.setKey(hmacKey).</p><p>In the JWT consumer, we only need to set the HMAC key by using .setVerificationKey(hmacKey) on the jwtConsumer object jose4j will automatically determine which algorithm is used in the JWS by parsing its JOSE header.</p><h3>ES256</h3><p>Unlike the HS256 that only needs one key, we need to generate two keys for the ES256 algorithm: private and public keys.</p><p>We can use the private key to create and verify the JWT, while we can only use public keys to verify the JWT. Due to those traits, a private key is usually stored as a credential, while a public key can be hosted in public as JWK so the consumer of the JWT can query the host and get the key by themself.</p><p>jose4j library provides a simple API to generate private and public keys as a JWK.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6a87d392038cd57d8aaff86c055b46e/href">https://medium.com/media/f6a87d392038cd57d8aaff86c055b46e/href</a></iframe><p>Now that we know how to generate the key creating the JWT with the ES256 algorithm, it is almost the same as creating a JWT with the HS256 algorithm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a740ea4eda4c89f58ef5b636b402b6/href">https://medium.com/media/e7a740ea4eda4c89f58ef5b636b402b6/href</a></iframe><p>The only different things are:</p><ul><li>We set the algorithm header as ECDSA_USING_P256_CURVE_AND_SHA256</li><li>We use the private key when creating the JWT</li><li>We use the public key for verifying the JWT</li></ul><h3>Hosting JWK</h3><p>We can easily create JSON Web Key Set using the JsonWebKeySet class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e64f94acd4640b87147dd1b38d7290d/href">https://medium.com/media/7e64f94acd4640b87147dd1b38d7290d/href</a></iframe><p>We also need to change some properties of the key resolver:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5408a69f08b7c93600ace99f506daa4e/href">https://medium.com/media/5408a69f08b7c93600ace99f506daa4e/href</a></iframe><p>Since we hosted the JSON Web Key Set, we need to query the host. jose4j is also providing a simple way to do this by using HttpsJwksVerificationKeyResolver.</p><h3>Implementing JWE in Java</h3><p>JSON Web Encryption, unlike JWS, is a type of JWT that is encrypted so that no one can see its content except the one with the private key. First, let’s see an example of it:</p><pre>eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiMEdxMEFuWUk1RVFxOUVZYjB4dmxjTGxKanV6ckxhSjhUYUdHYzk5MU9sayIsInkiOiJya1Q2cjlqUWhjRU1xaGtubHJ6S0hVemFKMlhWakFpWGpIWGZYZU9aY0hRIiwiY3J2IjoiUC0yNTYifX0.DUrC7Y_ejpt1n9c8wXetwU65sxkEYxG6RBsCUdokVODJBtwypL9VjQ.ydZx-UDWDN7jbGeESXvPHg.6ksHUeeGgGj0txFNXmsSQUCnAv52tJuGR5vgrX54vnLkryPFv2ATdLwYXZz3mAjeDes4s9otz4-Fzg1IBZ4qsfCVa6_3CVdkb8BTU4OvQx23SFEgtj8zh-8ZrqZbpKIT.p-E09mQIleNCCmwX3YL-uQ</pre><p>The structure of the JWE is:</p><pre>BASE64URL(UTF8(JWE Protected Header)) || ’.’ ||<br>BASE64URL(JWE Encrypted Key) || ’.’ ||<br>BASE64URL(JWE Initialization Vector) || ’.’ ||<br>BASE64URL(JWE Ciphertext) || ’.’ ||<br>BASE64URL(JWE Authentication Tag)</pre><p>And if we decrypt the JWE, we will get the following claims:</p><pre>{<br>	&quot;iss&quot;:&quot;https://codecurated.com&quot;,<br>	&quot;exp&quot;:1654274573,<br>	&quot;iat&quot;:1654256573,<br>	&quot;sub&quot;:&quot;12345&quot;<br>}</pre><p>Now, let’s see how we create the JWE:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04906b87f6470e96c1c2e9b7d60aa92c/href">https://medium.com/media/04906b87f6470e96c1c2e9b7d60aa92c/href</a></iframe><p>The main difference between creating and consuming JWE compared to JWS are:</p><ul><li>We use a public key as the encryption key and a private key as the decryption key</li><li>We don’t have a signature in JWE, so the consumer will need to skip the signature requirement</li></ul><h3>Conclusion</h3><p>In this article, we’ve learned to create both JWS and JWE in Java using jose4j.</p><p>I hope this article is useful to you. If you want to learn more about the concept of JWT, you can visit <a href="https://codecurated.com/blog/introduction-to-jwt-jws-jwe-jwa-jwk/">my other article.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=943084ad1592" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-implement-json-web-token-jwt-in-java-spring-boot-943084ad1592">How To Implement JSON Web Token (JWT) in Java Spring Boot</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to JWT (Also JWS, JWE, JWA, JWK)]]></title>
            <link>https://medium.com/bliblidotcom-techblog/introduction-to-jwt-also-jws-jwe-jwa-jwk-e845b0db9f4e?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e845b0db9f4e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Wed, 11 May 2022 09:55:18 GMT</pubDate>
            <atom:updated>2022-05-11T09:55:18.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to JWT</h3><h4>Also JWS, JWE, JWA, and JWK</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*hSVBH9HnB3vsMeky" /></figure><p>The security and privacy of users’ data have been a growing concern for the past few years. At the same time, JWT, as one technology to combat it, has been used more and more. Understanding JWT will give you an edge over the other software engineers. JWT might seem simple at first, but it is pretty hard to understand.</p><p>In this article, we will explore mainly JWT and JWS. In addition, we’ll also go through JWE, JWA, and JWK quickly. This article aims to make the reader understand the concept of JWT without diving too deep into the topic.</p><h3>What Are They?</h3><p>Before taking a deeper look, it‘s better if we know the connection between JWT, JWS, JWE, JWA, and JWK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*zU2mJ9L7bRTTMdy0FSRjIA.png" /></figure><p>From the diagram above, we can see that:</p><ul><li><strong>JSON Web Token (JWT)</strong> is an abstract that is represented in the form of <strong>JSON Web Signature (JWS)</strong> and <strong>JSON Web Encryption (JWE)</strong>.</li><li><strong>JSON Web Signature (JWS)</strong> and <strong>JSON Web Encryption (JWE)</strong> use signature and encryption algorithms defined in <strong>JSON Web Algorithm (JWA)</strong> as a way of securing themselves.</li><li>The public key of the signature algorithm defined in <strong>the JSON Web Algorithm (JWA)</strong> can be hosted as <strong>JSON Web Key (JWK)</strong>.</li></ul><p>Now that we know their relationship, let’s take a deeper look at the JWT, JWS, JWE, JWA, and JWK.</p><h4>JSON Web Token (JWT)</h4><p>First, let’s see the definition of JWT defined in the <a href="https://datatracker.ietf.org/doc/html/rfc7519">RFC 7519</a>.</p><blockquote>JSON Web Token (JWT) is a compact claims representation format<br> intended for space constrained environments such as HTTP<br> Authorization headers and URI query parameters. JWTs encode claims<br> to be transmitted as a JSON object that is used as the<br> payload of a JSON Web Signature (JWS) structure or as the<br> plaintext of a JSON Web Encryption (JWE) structure, enabling<br> the claims to be digitally signed or integrity protected with a<br> Message Authentication Code (MAC) and/or encrypted. JWTs are always<br> represented using the JWS Compact Serialization or the JWE Compact<br> Serialization.</blockquote><p>From the text, we can understand that JWT is not a structure but a set of claims in the shape of either JWS or JWE as its way of securing itself. In the most basic form, the difference between JWS and JWE is that everyone can see the payload of JWS while the JWE one is encrypted.</p><p>In this article, we will explore more about JWS than JWE.</p><h4>JSON Web Algorithm (JWA)</h4><p>JWA (<a href="https://datatracker.ietf.org/doc/html/rfc7518">RFC 7518</a>), which stands for JSON Web Algorithm, is a specification defining which signature and encryption algorithm to make a JWT.</p><p>For example, the following are the hashing algorithms we can use to create a JWT with a JWS structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*8o3o_bHoSv6Kb2Hq.png" /></figure><h4>JSON Web Key (JWK)</h4><p>JWK (<a href="https://datatracker.ietf.org/doc/html/rfc7517">RFC 7517</a>) stands for JSON Web Key. JWK is a JSON data structure that contains information about signature algorithm cryptographic key. It’s a way to store your hashing key in JSON format.</p><pre>{<br>    &quot;kty&quot;:&quot;EC&quot;,<br>    &quot;crv&quot;:&quot;P-256&quot;,<br>    &quot;x&quot;:&quot;f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU&quot;,<br>    &quot;y&quot;:&quot;x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0&quot;,<br>    &quot;kid&quot;:&quot;Public key used in JWS spec Appendix A.3 example&quot;<br>}</pre><p>The JWK is usually used to host a public key for a hashing function with an asymmetric key (private key and public key), so the consumer can get the key by themselves.</p><h4>JSON Web Signature (JWS)</h4><p>JWS (<a href="https://datatracker.ietf.org/doc/html/rfc7515">RFC 7515</a>), which stands for JSON Web Signature, is one of the structures used by JWT. It’s the most common implementation of the JWT. JWS consists of 3 parts: the JOSE (JavaScript Object Signing and Encryption) header, payload, and signature.</p><p>The following is an example of JWS in compact serialization.</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</pre><p>If we decode the JWS, we will get JOSE header:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>The payload:</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;John Doe&quot;,<br>  &quot;iat&quot;: 1516239022<br>}</pre><p>The next part is the signature. We won’t decode it because it’s in bytes values.</p><pre>SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</pre><p>The most common question related to JWT (in JWS structure) is what makes it secure since everyone can decode the JWT and see its data. The JWT is secure because we can confirm who created the JWT by verifying its signature.</p><h4>JSON Web Encryption (JWE)</h4><p>JWE, unlike JWS, encrypts its content using an encryption algorithm. The only one that can see what is inside the JWT is the one with the key.</p><p>The structure of JWE compact serialization is as follows:</p><pre>BASE64URL(UTF8(JWE Protected Header)) || ’.’ ||<br>BASE64URL(JWE Encrypted Key) || ’.’ ||<br>BASE64URL(JWE Initialization Vector) || ’.’ ||<br>BASE64URL(JWE Ciphertext) || ’.’ ||<br>BASE64URL(JWE Authentication Tag)</pre><p>Let’s take a look at one example:</p><pre>eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.qU0jHnBEySevrLJ9KQWx1ACqddpYTM0llhGCRnBbNhIZvQBgRCEXMnDCDnfRiTptyGM1OXD9Ih_OL-FQUcwh8A7A1-WqsZ6jaIjR3MeKwWdPu7HLv_FZIlqit-5vCSEIzQT0Sytvz4YLGg0RVGSHR_1XMHmSgdVUF9xwAIVLndhYkwdgNKxcjGmwGpgrxxvvh102lzvViar4k4kPzjVw3l73mbMkuoY0e7zJo8qWBHNMa7i9lDgtvyedhgu3CR0oEQOrt0krGYHvMFBt0qv1BP5NZeQrnSkB7ENSL_5XxRUpxWLzpTZihu7CDxL3EAj5t3wE7N_4g1rQX8tJ-9DRKg.WzuKJ1_ISPo_bjLrAZZqYA.Fi2ZzOF2cAf8QdQdgDcqCWzNFbQKUdtyAIXq5j6PdOXOXVtyf4uE3ew74UwE4N_GAwUUX13XEbAnzDf3VuGfUQ.QAh8Apx_sQ7AE0C6-90YQg</pre><p>The example uses the RSA_OAEP_256 key management algorithm and AES_128_CBC_HMAC_SHA_256 as its encryption algorithm. If we decrypted the JWE, we will get:</p><pre>{<br>  &quot;exp&quot;:1652259503,<br>  &quot;iat&quot;:1652259203,<br>  &quot;sub&quot;:&quot;12345&quot;<br>}</pre><h4>Decoding the JWT</h4><p>Now let’s take a deeper look at the JWT by using the following example:</p><pre>eyJhbGciOiJIUzI1NiIsImtpZCI6IjIwMjItMDUtMDEifQ.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJyaWxpYW4gRmlyZGF1cyIsImlhdCI6MTY1MTQyMjM2NX0.qsg3HKPxM96PeeXl-sMrao00yOh1T0yQfZa-BsrtjHI</pre><p>The JWT in the example is a JWT with JWS compact serialization structure. We need to split the JWT by . (dot), and Base64 decode them to look at what&#39;s inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VcIZfA-PgpwCaoiT.png" /><figcaption>Breaking down the JWT</figcaption></figure><p>After splitting and decoding the JWT, we will get three parts:</p><ul><li>JOSE (JavaScript Object Signature and Encryption) Header</li><li>Payload</li><li>Signature</li></ul><h4>JOSE Header</h4><pre>eyJhbGciOiJIUzI1NiIsImtpZCI6IjIwMjItMDUtMDEifQ</pre><p>After doing a Base64 decode on the string, we will get:</p><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;kid&quot;: &quot;2022-05-01&quot;<br>}</pre><p>This part of JWT is called the JOSE header. With the JOSE header, the JWT can inform the client how to handle the JWT.</p><p>Let’s break down the two fields we have in our JWT:</p><ul><li>alg: contains the information regarding the signing algorithm of the JWT.</li><li>kid: contains the information of the id of the key used for verifying the JWT. We will explore more about this in the JWK section.</li></ul><p>alg is the only mandatory header, and it&#39;s the only one needed for most cases, but there are many more headers you can check <a href="https://datatracker.ietf.org/doc/html/rfc7515#section-4">here</a>.</p><h4>Payload</h4><p>With the JOSE header out of the way, let’s take a look at the second part, the payload.</p><pre>eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJyaWxpYW4gRmlyZGF1cyIsImlhdCI6MTY1MTQyMjM2NX0</pre><p>After we decode it:</p><pre>{<br>  &quot;sub&quot;: &quot;1234567890&quot;,<br>  &quot;name&quot;: &quot;Brilian Firdaus&quot;,<br>  &quot;iat&quot;: 1651422365<br>}</pre><p>This part of the JWT is called the payload. There are fields with the term JWT claims ( sub, name, iat). So, now seems like a good time to talk about JWT claims.</p><p>There are three types of JWT claims:</p><ul><li>Registered Claims</li><li>Public Claims</li><li>Private Claims</li></ul><p>Let’s break it down one by one, starting from Registered Claims. Registered claims are claims that have been documented initially in the RFC 7519.</p><ul><li>iss (Issuer): indicates who is the issuer of the JWT.</li><li>sub (Subject): indicates the user&#39;s id requesting the JWT.</li><li>aud (Audience): shows who&#39;s the intended consumer of the JWT.</li><li>exp (Expiration): the expiration time of the JWT.</li></ul><p>You can check the complete list <a href="https://datatracker.ietf.org/doc/html/rfc7519#section-4.1">here</a>. None of these claims are mandatory, as dictated in the <a href="https://datatracker.ietf.org/doc/html/rfc7519">RFC 7519</a>, but they are essential in securing your JWT.</p><p>The next type of claim we’ll explore is private claims. These claims can be anything. It’s up to the JWT creator or consumer to determine the claims name and function.</p><p><strong>Warning</strong>: When specifying private claims, you need to be careful not to cause any collision in the name.</p><p>The last one is public claims, which is a type of claim that is publicly registered through IETF. You can check the list of public claims at: <a href="https://www.iana.org/assignments/jwt/jwt.xhtml#claims">https://www.iana.org/assignments/jwt/jwt.xhtml#claims</a>.</p><p>Most people don’t have any use case needing them to register their claims. For best practice, you can search the list of Public Claims and use the one suitable for your use case.</p><h4>Signature</h4><p>If you’ve come to this part, you might wonder what makes the JWT secure since everyone can see its content. Well, the payload of the JWS is intended for everyone to read. What makes the JWT safe is the consumer can verify who is the one issued the JWT.</p><p>The signature part in JWT is created by using a hash function. If you’re not familiar with a hash function, it’s an algorithm that maps an object to another object. A hash function has two important traits which make it suitable to secure the JWT:</p><ul><li>It only works one way</li><li>The results of hashing process are always the same</li></ul><p>In this article, we’ll explore 2 of the most common signature algorithms used in JWT:</p><ul><li>HS256</li><li>ES256</li></ul><p>Now, let’s break apart the signature we use in the example:</p><pre>qsg3HKPxM96PeeXl-sMrao00yOh1T0yQfZa-BsrtjHI</pre><p>Which is generated using HS256 MAC algorithm with secret key (in base64) :</p><pre>7TgIAQCcYUA27bCI5+m7InRwp/mzQ+ArnFW/4c0Q51U=</pre><p>The HS256 MAC algorithm receives bytes value as its secret key parameter and produces bytes value as its output. So, unlike the header and the payload, we will get bytes value if we try to decode the signature.</p><p>Let’s explore the digital signature or MAC algorithm more thoroughly.</p><h4>HMAC SHA-256</h4><p>The first algorithm we’ll explore is HMAC SHA-256 (HS256), a MAC algorithm using a hash function with a symmetric key. Hashing function with a symmetric key means only one key for the hashing function. So, the producer and consumer of the JWT will use the same key to sign and verify the JWT. The advantage of using this algorithm is it doesn&#39;t need many CPU resources to create the hash.</p><p><strong>Note: </strong>The minimum bytes length recommended for the HS256 secret key is 32 bytes. The secret key must be generated with a Cryptographically-secure pseudorandom number generator to ensure its randomity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wTFIg7ufkfSPsdrB.png" /><figcaption>HS256 Example</figcaption></figure><h4>ES256</h4><p>ES256, unlike HMAC, is an algorithm that uses hashing function with an asymmetric key. Hashing function with an asymmetric key means we will need to generate two keys. One key is called a private key, which can be used to both sign and verify the JWT signature. The other key is called a public key, which can only be used to verify the JWT signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*cMTVgVJzJhjdzFF-.png" /><figcaption>Private and Public Key in ES256</figcaption></figure><p>As their names imply, a public key can be stored in a public space (usually as a JWK), so the client that needs to verify your JWT signature can get it quickly. In contrast, a private key must be secured and treated as a credential.</p><h4>Which Algorithms to Choose?</h4><p>We have learned two algorithms, HS256 and ES256, but when to choose one instead of another? You can easily decide about it by thinking about whether the producer and the consumer of the JWT are not the same components.<br>If the consumer of the JWT is the same component, then you can use the HS256 algorithm. This hashing function&#39;s most common use case is when you&#39;re making an authentication system using JWT.</p><p>On the other hand, if the JWT is produced and consumed by a different component, you can use ES256. This way, you can secure your key and ensure that no one else (even the public key owner) can create a JWT on your behalf.</p><p><strong>Warning</strong>: Some people consider HS256 a kind of anti-pattern because JWT is supposedly used to increase security, but most of the use case that uses this algorithm decreases security.<br>For example, suppose you plan to use JWT as an authentication session instead of a database. In that case, your system is more insecure because you can’t expire the JWT, so you can’t kick sessions.</p><h4>Storing Public Key as JWKs (JSON Web Key Set)</h4><p>If you plan to let the public to consume and verify your JWT, it’s recommended to host the public key as JWKs on a URL. This way, if the consumer wants to verify your JWT, they can query a specific URL hosting the JWKs and get the public key.</p><pre>{<br>  &quot;keys&quot;: [<br>    {<br>      &quot;kty&quot;: &quot;EC&quot;,<br>      &quot;kid&quot;: &quot;2022-05-01&quot;,<br>      &quot;x&quot;: &quot;g_pYyqY7Htj8Aa989Ura0_mwRdqJPEnhknKzaUrztj8&quot;,<br>      &quot;y&quot;: &quot;MwOFYLE-VYre92hU0iDjNx36dk7cX6xdGgdgLIPt6Ts&quot;,<br>      &quot;crv&quot;: &quot;P-256&quot;<br>    },<br>    {<br>      &quot;kty&quot;: &quot;EC&quot;,<br>      &quot;kid&quot;: &quot;2020-01-01&quot;,<br>      &quot;x&quot;: &quot;6bw04ZlSMjxVzC7gXv75XAposOVTONh45ZPR0AeYaoU&quot;,<br>      &quot;y&quot;: &quot;vYyCSIt0m5k4Q5A_uW8h3nEYJvgA8PgREErLcaiAHgQ&quot;,<br>      &quot;crv&quot;: &quot;P-256&quot;<br>    }<br>  ]<br>}</pre><p>You might’ve noticed more than one key in the JSON, which is why it’s called JSON Web Key <strong>Set</strong>. If your product uses more than one key, you can host every key in the JWKs. To identify which key to use, you will need to add the kid or key id field in your JOSE Header.</p><pre>{<br>    &quot;alg&quot;:&quot;ES256&quot;,<br>    &quot;kid&quot;:&quot;2022-05-01&quot;<br>}</pre><p>This way, the client will know which key to get by comparing the kid in the JOSE header JWT to the one in the JWK. The other fields, combined, will make the public key.</p><h4>Takeaway</h4><p>In this article, we’ve learned that:</p><ol><li>JWT is an abstract about how to allow one or more parties to exchange information securely. The implementation of JWT comes in the form of JWS or JWE.</li><li>The difference function between JWS and JWE is that JWS allows everyone to see its payload, while JWE doesn’t allow it by using an encryption method.</li><li>What makes JWS considered secure even though everyone can see its payload is that the creator of the JWS can be verified by its signature using MAC or Signature Verifying algorithm. This way, the consumer can be sure that the one created the JWT is the one intended.</li><li>We’ve explored two types of algorithms, HS256 and ES256. HS256 is suitable when the producer and the consumer of the JWT are the same components, while ES256 is suitable when the producer and the consumer are different components.</li><li>We can use JSON Web Key Set to host a public key for hashing function with an asymmetric key. You need to set the kid field in the JOSE header of your JWT so the consumer can compare it to the one in the JWKs to get a compatible key.</li></ol><p>Alas, I want to thank you for reading until the end. The next step you can take is to learn how to implement it. There are many libraries for popular programming languages that you can check <a href="https://jwt.io/libraries">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e845b0db9f4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bliblidotcom-techblog/introduction-to-jwt-also-jws-jwe-jwa-jwk-e845b0db9f4e">Introduction to JWT (Also JWS, JWE, JWA, JWK)</a> was originally published in <a href="https://medium.com/bliblidotcom-techblog">Blibli.com 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[Getting Started With Docker in 2021]]></title>
            <link>https://medium.com/better-programming/getting-started-with-docker-in-2021-8df187f5979d?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8df187f5979d</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Wed, 14 Apr 2021 17:38:58 GMT</pubDate>
            <atom:updated>2021-04-14T17:38:58.420Z</atom:updated>
            <content:encoded><![CDATA[<h4>Everything you need to know about Docker</h4><figure><img alt="Whale in the ocean" src="https://cdn-images-1.medium.com/max/1024/0*R-b79MxbTL-CU2JZ" /><figcaption>Photo by <a href="https://unsplash.com/@toddcravens?utm_source=medium&amp;utm_medium=referral">Todd Cravens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>For the past few years, Docker has been disrupting the development and DevOps fields. Many people think Docker is a programming language or framework. It is not. Docker is an open source platform for building, shipping, and running containers.</p><p>It is a tool that allows you to manage images and containers. Because of that, before we cover Docker, it’s better if we learn about containers first.</p><h3>Containers</h3><p><a href="https://www.docker.com/why-docker">According to Docker</a>, “Containers are a standardized unit of software allowing developers to isolate their app from its environment.” By using a container, you no longer need to worry about the dependencies of your app clashing with each other. Every dependency that an app needs can be installed and isolated in a container. Also, we can guarantee that an app that runs in one container can also run in others.</p><h4>Advantages of using container</h4><p>So, why do we even use containers? What are the benefits? Well, to answer this question simply, isolation and limitation.</p><p>By using a container, we can isolate specific apps with the other components in the host machine (the machine on which we are using Docker). By default, the container won’t be able to access any of the host machine’s storage and the same thing applies vice versa. There are many things that isolation and limitation behavior solve, but let’s focus on two main things: dependency conflicts and limiting malware damage.</p><h4>Avoiding dependency conflicts</h4><p>I’m pretty sure everyone has experienced a dependency conflict on their personal computer. When you install a good deal of software on your PC, there is a chance of a conflict between the dependencies of the software.</p><p>For example, you want to install Software A and Software B. Software A requires you to have Python 2.1 installed within your PC, while software B requires Python 2.3. When you’re installing Software A, it works perfectly. But after you’ve installed Software B, your PC replaces Python 2.1 with version 2.3. Because some features are different between Python 2.3 and 2.1, Software A might not work anymore. This kind of thing often happens in the production server too.</p><p>To make everything work perfectly, you’ll need to work around the dependency conflict.</p><p>We can avoid dependency conflicts by using containers in our app system. Containers are isolated from each other and even their host machine, so dependency conflicts are not possible.</p><h4>Limiting the damage of a virus</h4><p>Whether it’s an accident or not, some software you use might contain a virus. If a software with a virus is run without using any resource isolation, it will be able to access the whole host machine. If it’s run inside a container, though, it won’t be able to access anything more than it’s allowed to. Because of that, you can think of a container as a jail for the running process inside it. Within a container, the virus won’t be able to access files outside of the container. It also can’t access the hardware resources (CPU and memory) easily because containers can also limit the hardware resources that they use.</p><h3>Container vs. Virtual Machine</h3><p>If you’ve been a developer for some time, chances are you’ve heard of or even used a virtual machine. Containers and virtual machines are pretty similar. They both isolate and limit a process within them. So, why use containers as opposed to virtual machines?</p><p>A VM is a piece of software that hosts a whole OS on it and runs on top of a physical machine called a hypervisor. Meanwhile, a container provides an isolated space that runs on top of its host OS.</p><p>The most important advantage of containers is the speed of initializing a new instance. Creating a VM requires minutes because you need to create a virtual disk, install the OS, allocate resources, etc. Containers use your host machine’s OS, disk, ram, CPU, etc. This makes creating a container very quick (usually a matter of seconds).</p><p>Another advantage is portability. In Docker, we can use the image for packaging the data of a container (we’ll learn about this later in the article). For a VM, though, if you want to package it, you’ll need to wrap the whole OS with its system data, producing a package of enormous size.</p><p>One thing to note is that there’s nothing wrong with having containers inside a VM. Actually, many people use them like that. You can rent a VM inside a cloud server like GCP, AWS, or DigitalOcean and run many containers inside it.</p><figure><img alt="Diagram comparing container vs. VM structure" src="https://cdn-images-1.medium.com/max/695/1*_qx4HZhjeyapBCMn3rQvag.png" /><figcaption>Container vs. VM structure</figcaption></figure><h3>Introduction to Docker</h3><p>As we learned in the previous section, Docker is an open source platform for building, shipping, and running containers. Docker runs on top of Linux OS by default. If you install Docker on Windows or macOS, it will ask you to install a Linux VM so it can run on top of it.</p><p><em>Note: Docker is currently not supported in Apple’s new M1 CPU architecture. There is a developer preview, but it isn’t stable yet.</em></p><h4>“Hello world” with Docker</h4><p>For this section, you’ll need to first install <a href="https://www.docker.com/products/docker-desktop">Docker Desktop</a>. After you’ve done installing it, you can verify your installation with the command docker -v. In my case, I&#39;m using Windows and my installed docker version is 19.03.12.</p><figure><img alt="Installing Docker" src="https://cdn-images-1.medium.com/max/1024/0*tWXks8lMqKKKN9Ew.png" /></figure><p>After you’ve successfully installed Docker, you can try running a “hello world” Docker image with docker run hello-world. You should get a result like this:</p><figure><img alt="Hello world in Docker" src="https://cdn-images-1.medium.com/max/1024/0*Kh4-m6LFHS8WtN2P.png" /></figure><p>So, what do you think about the result? Did you notice the line Unable to find image ‘hello-world:latest’ locally? What actually happened when we ran the previous command?</p><p>The first thing you need to know is Docker image. A Docker image is basically a snapshot of a container that has been configured previously. In the case of our “hello world” image, it’s configured to show the message as soon as the container is started.</p><p>So, what happened when we ran the command?</p><figure><img alt="Diagram explaining how Docker works" src="https://cdn-images-1.medium.com/max/619/1*yYD4_N79RkjObA7hxfvtEw.png" /></figure><ol><li>Docker got the docker run hello-world command.</li><li>Docker checked whether the hello-world image is in the image cache.</li><li>The image cache returned nothing, showing that the hello-world image is not in the image cache.</li><li>Docker checked Docker Hub (Docker’s public repository) for the hello-world image.</li><li>Docker Hub found an image tagged with hello-world:latest and returned it to the Docker on your machine. Note that you will get the latest tag by default if you don’t specify the tag version.</li><li>Docker then created a container from the image it got, displaying the output in your terminal screen.</li></ol><h3>Basic Commands</h3><p>Now that we understand how to run an image with docker run, let’s learn some basic commands.</p><h4>docker run</h4><p>We used docker run for our “hello world” example. docker run is basically a combination of docker pull, docker create, and docker start. To put it simply, docker pull is used to pull an image from the Docker registry to your image cache, docker create is used to create a container based on the image, and docker start is used to start a container.</p><p>docker run has many parameters you can send to it. Some of the most used ones are --rm, --name, and -it.</p><p>When you start a container with --rm, Docker will remove your container when it is stopped. This is useful if you want to keep your machine clean and free of unused containers.</p><p>--name will give the container a name. If you set a name for the container, you can then interact with the container by its name instead of just its ID.</p><p>The -it argument exposes the input and output of the container so you can interact with it.</p><h4>Running with a custom command</h4><p>When creating a Docker image, you can specify a default command that will be executed when you’re running the container from an image. For our hello-world image, its default command will open a script that displays some output in the container. But what if the image doesn’t have any default command? Or what if we want to use a custom command instead of the default one?</p><p>For the example in this section, we’ll use a busybox image, which is an image that provides several Unix utilities. busybox doesn&#39;t have a default command, which makes it perfect for our example.</p><p>Let’s try running the busybox image with docker run busybox:</p><figure><img alt="Running the busybox image with docker run busybox" src="https://cdn-images-1.medium.com/max/1024/0*O-O_oKMLJzKCFrwl.png" /></figure><p><em>Note: There will be an image-pulling process if you haven’t run the </em><em>busybox image before. I’ve run the </em><em>busybox image before, so there isn&#39;t an image-pulling process.</em></p><p>Nothing happened, right? There is a slight delay after you typed the command, but it displays nothing after that. busybox doesn’t have a default command, so it just stops itself after we run it.</p><p>Now, let’s try docker run -it busybox /bin/sh:</p><figure><img alt="Running the busybox image with docker run -it busybox /bin/sh" src="https://cdn-images-1.medium.com/max/1024/0*kmKXWmH1U1CztMT2.png" /></figure><p>Something happened! We’re actually accessing the container now! As we learned in the previous section, the -it argument exposes the input and output of the container so you can interact with the container.</p><p>The /bin/sh is the command you want to run when the container starts. If you have some basic understanding of Linux, you will know what it does. It will basically start a shell.</p><p>Now, let’s leave this terminal open and open a new one.</p><h4>docker ps</h4><p>docker ps is a command that will display every running container. If you want to display a non-running container too, you can add an -a argument.</p><p>Since we’re still running the busybox container, let’s use docker ps so we can see its information:</p><figure><img alt="Using docker ps" src="https://cdn-images-1.medium.com/max/1024/0*rZWN7cMQb-jlgv_i.png" /></figure><h4>docker exec</h4><p>If you want to run a command in a running container, you can use docker exec. Let’s try docker exec -it fcd /bin/sh:</p><figure><img alt="Using docker exec" src="https://cdn-images-1.medium.com/max/1024/0*PLY69eRUtzsushJq.png" /></figure><p>What does fcd in the command mean? fcd is actually the starting letter of the busybox container ID we ran before. We could see the container ID printed as fcd21cffad6e previously when we tried docker ps. Docker is a really smart software. It is able to identify which container you are pointing to even if you don&#39;t type the whole ID. As long as it&#39;s unique enough, Docker will be able to identify the container.</p><p>Now you can test that both of your terminals are accessing the same container by creating a folder and seeing whether the folder is also created in the other terminal:</p><figure><img alt="First container" src="https://cdn-images-1.medium.com/max/1024/0*O1PBy7CEDrvSYElQ.png" /></figure><figure><img alt="Second container" src="https://cdn-images-1.medium.com/max/937/0*CTkZEm_u0z5fhb0X.png" /></figure><p>In the first image, I created a directory called testing in the first terminal. After that, when I run an ls command in the second terminal, you can see that the directory is also there.</p><h4>docker logs</h4><p>To better visualize what the docker logs command does, let&#39;s use a redis image by running docker run -d redis.</p><p>docker logs {containerId} can be used to see the past console output of a container. If you want to follow the logs, you can also add the --follow argument. Let&#39;s see what our redis container that we just ran outputted by using docker logs 82. Note that the container ID on my machine and yours will be different.</p><figure><img alt="Using docker logs" src="https://cdn-images-1.medium.com/max/1024/0*uCGc0GswoOFbR3ms.png" /></figure><p>That’s it for the basic commands of Docker. If you’re interested in other commands, you can check them out in <a href="https://dockerlabs.collabnix.com/docker/cheatsheet/">this Docker Cheat Sheet</a>.</p><h3>Working With Volume</h3><p>Let’s jump into working with volume. In this section, there is only one thing I think you should know when you’re just starting to learn Docker: volume mounting.</p><p>Volume mounting is basically a way to connect your host OS’s volume with your container’s volume. This is a very important thing to know if you’re going to use Docker to host a container with persistent data storage. Without mounting the volume of your container to your host OS, your data will be wiped every time you update your image or create a new container.</p><p>To show how this works, let’s use the busybox image again. But before we start the container, create a folder somewhere in your machine. In my case, I’ll create a folder in D:/docker/test-busybox-volume. Let&#39;s also create a simple text file inside the folder we just created and name it whatever you want. I’ll name mine <a href="https://medium.com/mounted.txt">mounted.txt</a>.</p><p>It’s time to start busybox and mount it to the folder that we previously created! To use the mount volume feature, we can use docker run {image} --volume={src}:{dst}. Let’s try docker run --volume D:/docker/test-busybox-volume:/test-busybox -it busybox /bin/sh. Go to the /test-busybox directory and list the file inside using ls. You should see the file that you just created:</p><figure><img alt="Using the mount volume feature" src="https://cdn-images-1.medium.com/max/991/0*lBQS94DtpL_35rDv.png" /></figure><h3>Working With a Network</h3><p>There are two important things you need to know about networking in Docker:</p><ul><li>How to expose a port from the container to host the OS.</li><li>How containers can communicate with each other.</li></ul><p>For the example in this section, we’ll need an image with an exposed endpoint. I’ve created a simple image called brilianfird/node-mock-endpoint:1.0.0 that we can use for our case. The image contains an app that listens to port 8080 and will return a simple {&quot;success&quot;: true} response when it’s hit.</p><h4>Exposing a port</h4><p>Exposing a port from your port to your host OS is easy. You can add the --port {to}:{from} argument when starting a container. Let’s try it with the brilianfird/node-mock-endpoint image:</p><pre>docker run -p 8081:8080 brilianfird/node-mock-endpoint:<a href="https://medium.com/1.0.0">1.0.0</a></pre><p>After that, try opening localhost:8081 in your browser and you will see the response.</p><h4>Communication between containers</h4><p>It’s very normal these days for services to connect to each other because of the popularity of microservices. Most apps also need to connect to a database to operate properly. If containers are isolated, then how they can connect with each other?</p><p>For the containers to connect to each other, they’ll need to be in the same Docker network. In this article, we’ll use a very simple bridge network that can connect containers. If you’re interested in other kinds of networks, you can read about them in <a href="https://docs.docker.com/network/">the documentation</a>.</p><p>Let’s create a basic network with docker network create my-network and inspect it with docker network inspect my-network:</p><figure><img alt="Creating and inspecting a basic network" src="https://cdn-images-1.medium.com/max/1024/0*_dtagn9mCtG6IHAw.png" /></figure><p>There are many configs in a network, but in our case, Docker assigns everything by default because we didn’t specify them. We won’t deep-dive into what each config does. The only thing you need to know is that the “bridge” Driver will enable the containers within it to communicate with each other.</p><p>We’ll use two containers for this step: node-mock-endpoint and alpine. Let’s start the node-mock-endpoint images attached to our newly created network by running docker run --rm --network my-network --name my-endpoint -d node-mock-endpoint:<a href="https://medium.com/1.0.0">1.0.0</a>. Notice that we named the container. This is a very important thing to do to make other containers call this container more easily.</p><figure><img alt="Starting the node-mock-endpoint images" src="https://cdn-images-1.medium.com/max/1024/0*w51QvlBz1qX9ii8K.png" /></figure><p>The next step is to run an alpine image. We&#39;ll then install curl in the alpine image and try to access our node-mock-endpoint image from it. Let&#39;s run docker run --network my-network --rm -it alpine /bin/sh to create a new container. After you&#39;ve gotten in the container, run apk add curl --no-cache to install the curl command in your container:</p><figure><img alt="Installing the curl command" src="https://cdn-images-1.medium.com/max/1024/0*Lih4SUsgp1al5lAh.png" /></figure><p>Now, how do we call the node-mock-endpoint container? Well, when you create a container in a network, the Docker network will automatically assign a private IP to your container. Docker will also add an alias to the IP according to the container’s name. So, if you want to call a specific container, you can just call its name.</p><p>Previously, we named our node-mock-endpoint container my-endpoint. Since we can use the container&#39;s name to access it, we can just curl to my-endpoint and see whether it returns a response. Let’s run curl -XGET my-endpoint:8080:</p><figure><img alt="Running curl -XGET my-endpoint:8080" src="https://cdn-images-1.medium.com/max/788/0*ps7_f4LdZanmdLhD.png" /></figure><p>You should see the response {&quot;message&quot;:true} from the my-endpoint container if everything went fine.</p><h3>Creating Our Own Image in Docker</h3><p>Until now, we’ve only used the image that already exists in Docker Hub. But how do we actually create our own image? In this section, we’ll learn how to do just that! We’ll create a simple alpine image that has a curl pre-installed in it and will run curl --help as its default command.</p><p>We mostly only use custom commands to get inside a container’s shell. But remember that we can run any command that is compatible with the image (like installing the curl).</p><p>Let’s run an alpine container. This time, we’ll install the curl without going in the container. Let’s also name the container alpine-curl. For that, we can run docker run --name alpine-curl alpine apk add --no-cache curl.</p><p>Now, we have an alpine container that has curl installed. To create an image from it, we can use the docker commit command. First, let’s see how to use docker commit by running docker commit --help:</p><figure><img alt="Running docker commit — help" src="https://cdn-images-1.medium.com/max/792/0*vRP94LV2OMNQGrbN.png" /></figure><p>From the help response, we know that to use docker commit, we’ll need to at least specify the container, repository, and tag. The container is just the ID or name of the container you want to create an image from. The repository is the name of your image. It usually has this format: {company-name}/{image-name}. The tag is basically a version of your image. By default, Docker will use latest tag.</p><p>Now, back to our image. What’s left to do is to add the default command to our alpine-curl container. To do this, we can use the --change parameter with a CMD value in it when we commit. Let&#39;s run docker commit --change=&#39;CMD [&quot;curl&quot;, &quot;--help&quot;]&#39; alpine-curl brilianfird/alpine-curl:latest. Note that I used my Docker’s handle name as the {company-name}. You can use the same one or change it to your Docker’s handle name. We can then try running the brilianfird/alpine-curl image by using docker run brilianfird/alpine-curl, and we should see the curl help information.</p><p><em>Note: If you’re using windows and you’re getting </em><em>/bin/sh: [“curl”,: not found when running the image, try to commit the image in your WSL terminal.</em></p><figure><img alt="Running the brilianfird/alpine-curl image" src="https://cdn-images-1.medium.com/max/1024/0*2TNPr-j23NyAPclM.png" /></figure><p>Nice! Now our image is done! We created an image alpine-curl based on alpine image and installed the curl command in it. We then also added a default command curl --help that will be executed if we run the image!</p><p>Do you feel that creating an image is pretty complicated with all the commands you need to remember? Well, you’re not alone. I also feel that way! Thankfully, Docker provides an easier image creation process with Dockerfile.</p><h4>Creating an image with Dockerfile</h4><p>With Dockerfile, you can encompass all the docker commit commands within a single file with simpler syntax. Let’s create one for the alpine-curl image we created earlier.</p><p>First, let’s create a folder and name it alpine-curl. Then create a file named Dockerfile (without any extension) inside the folder we just created and insert the following text in it:</p><pre>FROM alpine<br><br>RUN apk add --no-cache curl<br>CMD [&quot;curl&quot;, &quot;--help&quot;]</pre><p>After that, run the docker build . command inside the alpine-curl folder. You&#39;ll get an image ID, and if you try to run it, you&#39;ll see the curl help information:</p><figure><img alt="curl help info" src="https://cdn-images-1.medium.com/max/1024/0*UB5WKd007lpiw-WQ.png" /></figure><p>One more thing we need to do is to change the image’s name. We can use <a href="https://docs.docker.com/engine/reference/commandline/tag/">docker tag</a> for that. Try running docker tag 63 brilianfird/alpine-curl-dockerfile:latest (remember to change the image ID).</p><p>After you’ve tagged the image, you can check whether it’s properly tagged by using docker images.</p><figure><img alt="Using docker images" src="https://cdn-images-1.medium.com/max/1024/0*sIOO_Xlp3KFz483j.png" /></figure><p>Now it’s very easy to create an image, right? Dockerfile is also what you would usually use to create an image of a development project.</p><h3>Docker Compose</h3><p>Until now, we’ve only talked about how to create a single-container application. What if we want to create a multi-container one? Well, Docker still has your back! You can use Docker Compose to create a multi-container Docker application.</p><p>Docker Compose is typically used for cases like development and the testing stage of an application. By using Docker Compose, if your application has a dependency to, for example, a MongoDB repository, you won’t have to install the Mongo in your machine. You can just add it to your Docker Compose file, and every time you run it, your application will start with the Mongo service.</p><p>Docker Compose will also make your life a lot easier when doing testing — especially integration testing. With it, you can be sure that the dependencies of your application in the local environment are the same as in production.</p><p>We used node-mock-endpoint and alpine-curl for earlier examples. For this section, we’ll use the same. We’ll create a Docker Compose that will run both node-mock-endpoint and alpine-curl with a single command and see whether they’re working as we expect.</p><p>For the example in this section, let’s first create a Dockerfile:</p><pre>FROM alpine<br><br>RUN apk add --no-cache curl<br>CMD [&quot;ping&quot;, &quot;google.com&quot;]</pre><p>The reason we’ll be pinging Google is so that the container won’t immediately exit when we run it.</p><p>Then, create a Docker Compose file. Go to your previously created alpine-curl folder and create a yml file named docker-compose.yml:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12fe87b60e7e0f36197879cf86ef9b18/href">https://medium.com/media/12fe87b60e7e0f36197879cf86ef9b18/href</a></iframe><p>Let’s discuss the <a href="https://medium.com/docker-compose.yml">docker-compose.yml</a> line by line.</p><ol><li>The first line is version. This determines which version of docker-compose you’re using.</li><li>services determine the services/images you want to run.</li><li>alpine-curl and mock-endpoint are the service names. You can name them whatever you want.</li><li>build asks Docker to build a Dockerfile for the specified service. You need to specify which Dockerfile will be built in the context. Since we’re using the default Dockerfile name (Dockerfile), we can just put a dot in there.</li><li>image means that you’ll run an image in the service. You can specify the repository, image name, and tag in there.</li></ol><p>Notice that we didn’t specify any network. When you’re using Docker Compose, every container will be able to communicate with each other by default. So even if we didn’t specify any network, alpine-curl would still be able to communicate with mock-endpoint.</p><p>Now let’s start Docker Compose by running docker-compose up --build in the terminal. The --build parameter is optional here, but if you change something in the Dockerfile/Docker Compose file, it’s better if you add the parameter to force Docker Compose to build your Dockerfile.</p><figure><img alt="Starting Docker Compose" src="https://cdn-images-1.medium.com/max/1024/0*TKEaJYzVN-uAqhvK.png" /></figure><p>With the docker-compose up command, Docker will parse the docker-compose.yml and create the containers of the defined images in the file.</p><p>To prove that both containers can communicate with each other, we can open a new terminal and get inside the alpine-curl container by running the command docker exec -it alpine-curl_alpine-curl_1 /bin/sh. Inside the container, try using a curl command (curl -XGET mock_endpoint:8080), and you should get a {&quot;message&quot;: true} response. The reason you can call the mock_endpoint is that Docker automatically resolves the services name to its private IP.</p><figure><img alt="Using curl -XGET mock_endpoint:8080" src="https://cdn-images-1.medium.com/max/874/0*uVY0Q5TuIwM2hGpF.png" /></figure><h3>Conclusion</h3><p>Docker is a very important component to learn for both software developers and DevOps. It’s the de facto standard when working with containers, which have so many advantages when compared to not using any.</p><p>In this article, we learned about Docker, but what’s next? We can learn how to use it in a real development project and also learn about Kubernetes, a Docker/container management system.</p><p>Finally, I’d like to say thank you for reading this article until the end! I hope you enjoyed it and got something from it!</p><h3>References</h3><ul><li><a href="https://docker.com/">Docker</a></li><li><a href="https://www.udemy.com/course/docker-and-kubernetes-the-complete-guide">Docker and Kubernetes: The Complete Guide on Udemy</a></li><li><a href="https://dockerlabs.collabnix.com/docker/cheatsheet/">The Ultimate Docker Cheat Sheet</a></li><li><a href="https://learning.oreilly.com/library/view/docker-in-action/9781617294761/">Docker in Action, Second Edition</a></li><li><a href="https://www.burwood.com/blog-archive/containerization-vs-virtualization#:~:text=Virtualization%20enables%20you%20to%20run,single%20virtual%20machine%20or%20server.">Containerization vs. Virtualization: What’s the Difference?</a></li></ul><p><em>Previously published at </em><a href="https://codecurated.com/blog/get-started-with-docker/"><em>codecurated.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8df187f5979d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-docker-in-2021-8df187f5979d">Getting Started With Docker in 2021</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Elasticsearch in Java Spring Boot]]></title>
            <link>https://medium.com/better-programming/getting-started-with-elasticsearch-in-java-spring-boot-d981c32b60b?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d981c32b60b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Thu, 04 Feb 2021 20:47:09 GMT</pubDate>
            <atom:updated>2021-02-04T20:47:09.664Z</atom:updated>
            <content:encoded><![CDATA[<h4>Connect Spring Boot with Elasticsearch</h4><figure><img alt="A laptop computer and a tea kettle resting on a table." src="https://cdn-images-1.medium.com/proxy/0*fyymAPzrwHiq6VDR" /></figure><p>Both Java and Elasticsearch are popular elements within common technology stacks that companies use. Java is a programming language that was released back in 1996. Java is owned by Oracle and still in active development.</p><p>Elasticsearch is a young technology compared to Java — it was only released in 2010 (making it 14 years younger than Java). It’s gaining popularity quickly and is now used in many companies as a search engine.</p><p>Seeing how popular both are, many people and companies want to connect Java with Elasticsearch in order to develop their own search engine. In this article, I want to teach you how to connect Java Spring Boot 2 with Elasticsearch. We’ll learn how to create an API that’ll call Elasticsearch to produce results.</p><h3>Connecting Java With Elasticsearch</h3><p>The first thing we must do is connect our Spring Boot project with Elasticsearch. The easiest way to do this is to use the client library provided by Elasticsearch, which we can just add to our package manager (like Maven or Gradle).</p><p>For this article, we’ll use a <a href="https://spring.io/projects/spring-data-elasticsearch">spring-data-elasticsearch</a> library provided by Spring Data, which also includes Elasticsearch’s <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high.html">High Level Client library</a>.</p><h4>Starting our project</h4><p>Let’s start by creating our Spring Boot project with <a href="https://start.spring.io/">Spring Initialzr</a>. I’ll configure my project to be like the picture below since we’re going to use a high-level client. Then we can use a convenient library provided by Spring, Spring Data Elasticsearch:</p><figure><img alt="Let’s start by creating our Spring Boot project with Spring Initialzr." src="https://cdn-images-1.medium.com/max/1024/0*bwv2vJx7BsZfROJc.png" /></figure><h4>Adding the dependency to Spring Data Elasticsearch</h4><p>If you followed my Spring Initialzr configuration in the previous section, then you should already have the Elasticsearch client dependency in your project. But if you don’t, you can add it:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-data-elasticsearch&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4>Creating the Elasticsearch client’s bean</h4><p>There are two methods to initialize the bean — you can either use the beans defined in the Spring Data Elasticsearch library, or you can create your own bean.</p><p>The easier option is to use the bean configured by Spring Data Elasticsearch.</p><p>For example, you can add these properties into your application.properties:</p><pre>spring.elasticsearch.rest.uris=localhost:9200<br>spring.elasticsearch.rest.connection-timeout=1s<br>spring.elasticsearch.rest.read-timeout=1m<br>spring.elasticsearch.rest.password=<br>spring.elasticsearch.rest.username=</pre><p>The second method involves creating your own bean. You can configure the settings by creating the RestHighLevelClient bean. If the bean exists, Spring Data will use it as its configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9a6bd8378258e062c1ad43130cca958/href">https://medium.com/media/a9a6bd8378258e062c1ad43130cca958/href</a></iframe><h4>Testing the connection from our Spring Boot application to Elasticsearch</h4><p>Your Spring Boot app and Elasticsearch should be connected now that you’ve configured the bean. Since we’re going to test the connection, make sure your Elasticsearch is up and running!</p><p>To test it, we can create a bean that’ll create an index in Elasticsearch in the DemoApplication.java. The class would look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fd61e428c80ec88ccc34e7466fd0bb4/href">https://medium.com/media/8fd61e428c80ec88ccc34e7466fd0bb4/href</a></iframe><p>OK, in that code we called Elasticsearch twice with the RestHighLevelClient, which we’ll learn later on in this article. The first call is to delete the index if it already exists. We used a try/catch that, because if the index, doesn’t exist. Then the elasticsearch will throw an error, failing our app’s starting process.</p><p>The second call is to create an index. Since I’m only running a single-node Elasticsearch, I configured the shards to be 1 and replicas to be 0.</p><p>If everything went fine, then you should see the indices when you check your Elasticsearch. To check it, just go to <a href="http://localhost:9200/_cat/indices?v">http://localhost:9200/_cat/indices?v</a>, and you can see the list of the indices in your Elasticsearch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ae5f36bb852106adbe1b4911683f571/href">https://medium.com/media/5ae5f36bb852106adbe1b4911683f571/href</a></iframe><p>Congrats! You just connect your application to the Elasticsearch!!</p><h3>Other ways to connect</h3><p>I recommend you use the spring-data-elasticsearch library if you want to connect to Elasticsearch with Java. But if you can’t use that library, there’s another way to connect your apps to Elasticsearch.</p><h4>High Level Client</h4><p>As we know from the previous section, the spring-data-elasticsearch library we used also includes Elasticsearch’s High Level Client. If you’ve already imported spring-data-elasticsearch, then you can already use Elasticsearch’s high-level client.</p><p>If you want to, it’s also possible to use the High Level Client library directly without Spring Data’s dependency. You just need to add this dependency in your dependency manager:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;<br>    &lt;artifactId&gt;elasticsearch-rest-high-level-client&lt;/artifactId&gt;<br>    &lt;version&gt;8.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>We’ll also use this client in our examples because the functionality in the High Level Client is more complete than that of spring-data-elasticsearch.</p><p>For more information, you can read the <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-getting-started.html">Elasticsearch documentation</a>.</p><h4>Low Level Client</h4><p>You’ll have a harder time with this library, but you can customize it more. To use it, you can add the following dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.elasticsearch.client&lt;/groupId&gt;<br>    &lt;artifactId&gt;elasticsearch-rest-client&lt;/artifactId&gt;<br>    &lt;version&gt;8.0.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>For more information, you can read <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-low.html">Elasticsearch’s documentation</a> about this.</p><h4>Transport client</h4><p>Elasticsearch also provides transport client, which will make your application identify as one of the nodes of Elasticsearch. I don’t recommend this method because it’ll be deprecated soon.</p><p>If you’re interested, you can read about the transport client <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html">here</a>.</p><h4>REST call</h4><p>The last way to connect to Elasticsearch is by doing a REST call. Since Elasticsearch uses the REST API to connect to its client, you basically can use a REST call to connect your apps to Elasticsearch. You can use OkHttp, Feign, or your web client to connect your apps with Elasticsearch.</p><p>I also don’t recommend this method because it’s a hassle. Since Elasticsearch already provides client libraries, it’s better to use them instead. Only use this method if you don’t have any other way to connect.</p><h3>Using Spring Data Elasticsearch</h3><p>First, let’s learn how to use spring-data-elasticsearch in our Spring project. spring-data-elasticsearch is very easy to use and a high-level library we can use to access Elasticsearch.</p><h4>Creating an entity and configuring our index</h4><p>After you’re done connecting your apps with Elasticsearch, it’s time to create an entity! With Spring Data, we can add metadata to our entity, which will be read by the repository bean we created. This way, the code will be much cleaner and faster to develop since we won’t need to create any mapping logic in our service level.</p><p>Let’s create an entity called Product:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e33f611883de6faaf4ce070b98241f8/href">https://medium.com/media/7e33f611883de6faaf4ce070b98241f8/href</a></iframe><p>So let me explain what’s going on in the code block above. First, I won’t explain about @Data, @AllArgsConstructor, @NoArgsConstructor, and @Builder . They’re annotations from the <a href="https://projectlombok.org/">Lombok library</a> for constructor, getter, setter, builder, and other things.</p><p>Now, let’s talk about the first spring data annotation in the entity, @Document. The @Document annotation shows that the class is an entity containing metadata of the Elasticsearch index’s setup. To use the Spring Data repository, which we’ll learn later on, the @Document annotation is mandatory.</p><p>The only annotation that’s mandatory in @Document is the indexName. It should be pretty clear from the name — we should fill it with the index name we want to use for the entity. In this article, we’ll use the same name as the entity, product.</p><p>The second parameter of @Document to talk about is the createIndex parameter. If you set the createIndex as true, your apps will create an index automatically when you’re starting the apps if the index doesn’t yet exist.</p><p>The shards, replicas, and refreshInterval parameters determine the index settings when the index is created. If you change the value of those parameters after the index is already created, the settings won’t be applied. So the parameters will only be used when creating the index for the first time.</p><p>If you want to use a custom ID in Elasticsearch, you can use @Id annotations. If you use @Id annotations, Spring Data will tell Elasticsearch to store the ID in the document and the document source.</p><p>The @Field type will determine the <a href="https://www.google.com/search?q=elasticsearch+mapping&amp;oq=elasticsearch+mapping&amp;aqs=chrome..69i57.2238j0j1&amp;sourceid=chrome&amp;ie=UTF-8">field mapping</a> of the field. Like shards, replicas, and refreshInterval, the @Field type will only affect Elasticsearch when first creating the index. If you add a new field or change types when the index is already created, it won’t do anything.</p><p>Now that we configured the entity, let’s try out the automatic index creation by Spring Data! When we configure the createIndex as true, Spring Data will check whether the index exists in Elasticsearch. If it doesn’t exist, Spring Data will create the index with the configuration we created in the entity.</p><p>Let’s start our app. After it’s running, let’s check the settings and see if it’s correct:</p><pre>curl --request GET \<br>  --url <a href="http://localhost:9200/product/_settings">http://localhost:9200/product/_settings</a></pre><p>The result is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5397f4722d781c48a6ef312838670867/href">https://medium.com/media/5397f4722d781c48a6ef312838670867/href</a></iframe><p>Everything is as we configured! The refresh_interval is set to 5s, the number_of_shards is 1, and number_of_replicas is 0.</p><p>Now let’s check the mappings:</p><pre>curl --request GET \<br>  --url <a href="http://localhost:9200/product/_mappings">http://localhost:9200/product/_mappings</a></pre><p>The result is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72457592268721deeab6fd94f2368c82/href">https://medium.com/media/72457592268721deeab6fd94f2368c82/href</a></iframe><p>The mappings are also as we expected. It’s the same as we configured in the entity class.</p><h4>Basic CRUD with the Spring Data repository interface</h4><p>After we’ve created the entity, we’ve everything we need to create a repository interface in Spring Boot. Let’s create a repository called ProductRepository.</p><p>When you’re creating an interface, make sure to extend ElasticsearchRepository&lt;T, U&gt;. In this case, the T object is your entity, and the U object type you want to use for the data ID. In our case, we’ll use the Product entity we created earlier as T and String as U .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/178aa15481d919cf0bdf36d9d0aa1062/href">https://medium.com/media/178aa15481d919cf0bdf36d9d0aa1062/href</a></iframe><p>Now that your repository interface is done, you don’t need to take care of the implementation because Spring is taking care of it. Now, you can call every function in the classes that your repository extends to.</p><p>For examples of CRUD, you can check the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ad9aa4eacdbb0a6508f26c6cff13f3/href">https://medium.com/media/60ad9aa4eacdbb0a6508f26c6cff13f3/href</a></iframe><p>In the code blocks above, we created a service class called SpringDataProductServiceImpl, which is autowired to the ProductRepository we created before.</p><p>There are four basic CRUD function in it. The first one is createProduct, which, as its name implies, will create a new product in the product index. The second one, getProduct, gets the product we’ve indexed by its ID. The deleteProduct function can be used to delete the product in the index by ID.The insertBulk function will allow you to insert multiple products to Elasticsearch.</p><p>Everything’s done! I won’t write about the API testing in this article because I want to focus on how our apps can interact with Elasticsearch. But if you want to try the API, I left a GitHub link at the end of the article so you can clone and try this project.</p><h4>Custom query methods in the Spring Data</h4><p>In the previous section, we only took advantage of using the basic methods that are already defined in the other classes. But we can also create custom query methods to use.</p><p>What’s very convenient about Spring Data is you can make a method in the repository interface, and you don’t need to code any implementation. The Spring Data library will read the repository and automatically create the implementations for it.</p><p>Let’s try searching for products by the name field:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5026433e61724b96d10727897ca5dbb1/href">https://medium.com/media/5026433e61724b96d10727897ca5dbb1/href</a></iframe><p>Yes, that’s all you need to do to create a function in the Spring Data repository interface.</p><p>You can also define a custom query with the @Query annotation and insert a JSON query in the parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6604b8fa376ecac920fe4b3c1bfb412e/href">https://medium.com/media/6604b8fa376ecac920fe4b3c1bfb412e/href</a></iframe><p>Both of the methods we’ve created do the same thing — use the match query with name as its parameter. If you try it, you’ll get the same results.</p><h4>Using ElasticsearchRestTemplate</h4><p>If you want to do a more advanced query, like aggregations, highlighting, or suggestions, you can use the ElasticsearchsearchRestTemplate provided by the Spring Data library. By using it, you can create your own query, making itas complex as you want.</p><p>For example, let’s create a function for doing a match query to the name field like before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac31c7c47ed305a9b59bd18f2d69bcd8/href">https://medium.com/media/ac31c7c47ed305a9b59bd18f2d69bcd8/href</a></iframe><p>You should notice the code above is more complex than the one we defined in the ElasticserchRepository. It’s recommended to use the Spring Data repository if you can. But for a more advanced query like aggregation, highlighting, or suggestions, you must use the ElasticsearchRestTemplate.</p><p>For example, let’s write a bit of code that’ll aggregate a term:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/253c521c3651aef72ce946c79948dd8f/href">https://medium.com/media/253c521c3651aef72ce946c79948dd8f/href</a></iframe><h3>Elasticsearch RestHighLevelClient</h3><p>If you’re not using Spring or your Spring version doesn’t support spring-data-elasticsearch, you can use a Java library developed by Elasticsearch, <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high.html">RestHighLevelClient</a>.</p><p>RestHighLevelClient is a library you can use to do basic things like CRUD or managing your Elasticsearch. Even though the name implies that it’s high level, it’s actually more low level when compared to spring-data-elasticsearch.</p><p>The advantage of this library over Spring Data is you can also manage your Elasticsearch with it. It provides index and Elasticsearch configuration, which you can use with more flexibility when compared to Spring Data. It also has more complete functionality to interact with Elasticsearch.</p><p>The disadvantage of this library over Spring Data is this library is more low level, which means you must code more.</p><h4>CRUD with RestHighLevelClient</h4><p>Let’s see how we can create a simple function with the library so we can compare it to the previous methods we’ve used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aa3795b4c834dd2605f5871f08aa18e/href">https://medium.com/media/0aa3795b4c834dd2605f5871f08aa18e/href</a></iframe><p>As you can see, it’s now more complicated and harder to implement. Now, you need to handle the exception and also convert the JSON result to your entity. It’s recommended to use Spring Data instead for basic CRUD operations because RestHighLevelClient is more complicated.</p><p>I’ve included other CRUD functions in the GitHub project. If you’re interested, you can check it out. The link is at the end of this article.</p><h4>Index creation</h4><p>This section is where the RestHighLevelClient holds a clear advantage compared to Spring Data Elasticsearch. When we were creating an index, with its mappings and settings, in the previous section, we only used annotations. It’s very easy to do, but you can’t do much with it.</p><p>With RestHighLevelClient, you can create methods for index management or basically almost anything that the Elasticsearch REST API allows.</p><p>For example, let’s write some code that’ll create the product index with the settings and mappings we used before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb4fe0228ed74add1f5fbe030c4d61b7/href">https://medium.com/media/eb4fe0228ed74add1f5fbe030c4d61b7/href</a></iframe><p>So let’s see what we did in the code:</p><ol><li>We initialized the createIndexRequest when also determining the index name.</li><li>We added the settings in the request when calling <a href="https://codecurated.com/blog/how-to-connect-java-with-elasticsearch/createIndexRequest.settings">createIndexRequest.settings</a>. In the settings, we also configured the field <a href="https://codecurated.com/blog/how-to-connect-java-with-elasticsearch/index.requests.cache.enable">index.requests.cache.enable</a>, which isn’t possible with the Spring Data library.</li><li>We made a Map containing the properties and mappings of the fields in the index.</li><li>We called Elasticsearch with <a href="https://codecurated.com/blog/how-to-connect-java-with-elasticsearch/restHighlevelClient.indices.create">restHighlevelClient.indices.create</a>.</li></ol><p>As you can see, with the RestHighLevelClient, we can create a more customized call for creating an index for Elasticsearch when compared to the annotations in the Spring Data entity. There’s also more functionality in the RestHighLevelClient that doesn’t exist in the Spring Data library. You can read <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html">Elasticsearch’s documentation</a> for more information about the library.</p><h3>Conclusion</h3><p>In this article, we’ve learned two ways to connect to Elasticsearch: using Spring Data and through Elasticsearch client. Both are powerful libraries, but you should only use Spring Data if it’s possible for your use case. The code with Spring Data Elasticsearch is more readable and easier to use.</p><p>If you want a more powerful library that can basically do anything Elasticsearch allows, though, then you can also use the Elasticsearch High Level Client. You can also use the Low Level Client, which we didn’t cover in this article, if you need even more powerful features.</p><p>I’d also like to say thank you for reading this article, and I hope this article is helping you to get started with Elasticsearch in Java Spring Boot. If you want to learn more about the libraries, you can check out <a href="https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#new-features">the Spring Data Elasticsearch documentation</a> and <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html">Elasticsearch’s High Level Client documentation</a>.</p><p>Below is the GitHub link for the GitHub project used for this article:</p><p><a href="https://github.com/brilianfird/elasticsearch-with-spring-boot">brilianfird/elasticsearch-with-spring-boot</a></p><p><em>Previously published at </em><a href="https://codecurated.com/blog/how-to-connect-java-with-elasticsearch/"><em>codecurated.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d981c32b60b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-elasticsearch-in-java-spring-boot-d981c32b60b">Getting Started With Elasticsearch in Java Spring Boot</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set up a Self-Hosted Ghost Blogging Platform]]></title>
            <link>https://brilianfird.medium.com/how-to-set-up-a-self-hosted-ghost-blogging-platform-3b016a35f614?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b016a35f614</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ghosts]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 16:33:44 GMT</pubDate>
            <atom:updated>2020-12-07T11:10:37.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setting up a self-hosted Ghost blogging platform with DigitalOcean, Namecheap and Cloudflare</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p992ccQ4HVCNbeyY" /><figcaption>Photo by <a href="https://unsplash.com/@tandemxvisuals?utm_source=medium&amp;utm_medium=referral">Tandem X Visuals</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently when <a href="https://codecurated.com/blog/reasons-i-changed-from-wordpress-to-ghost/">I changed my blog from WordPress to Ghost</a>, I’ve run to some problems because it was my first time setting up a Ghost blog. I decided to write this article on how to set up a self-hosted Ghost so you can avoid having the same problem as I am.</p><p><em>Disclaimer: this article contains 1 or more affiliate links.</em></p><h4>What is Ghost</h4><p>I’m sure if you opened this article, you already know at least a bit about Ghost. Ghost is a headless CMS built specifically for blogging built on top of JavaScript and NodeJS. It’s a very fast, doesn’t need a lot of resources and has clean UI UX. Ghost is first released in October 2013, making its age over 7 years as of this article.</p><h4>Why choose self-hosted Ghost</h4><p>You have two options if you want to use Ghost. The first option is to use their hosting service, and the second option is by hosting the Ghost at the server you choose.</p><p>Both options are good and have advantages and disadvantages. But the most notable different is the price.</p><p>The cheapest plan in hosted Ghost is <a href="https://ghost.org/pricing/">$29 a month</a> billed yearly, and it still doesn’t come with a free domain. It’s not suited for someone or a business that has just starting out.</p><p>If we compare it to DigitalOcean, the cheapest droplet we can buy is <a href="https://www.digitalocean.com/pricing/">$5 a month</a> billed monthly, I tested on my blog and it works just fine. We can also upgrade and downgrade the droplet as we want when we need it.</p><p>We can see that hosted Ghost is almost 6 times more expensive than self-hosted one. For that reason alone, you should consider using self-hosted Ghost.</p><h4>Accounts that you need for self-hosted Ghost</h4><p>In this section I will write about which account I created for my self-hosted Ghost. You don’t need to use the service I chose, but in this article I will only explain with the service I chose.</p><h4>Hosting</h4><p>I use <a href="https://m.do.co/c/533434bb8811">DigitalOcean</a> for hosting. I’ve heard a lot of good things about it, and I also have an enjoyable experience using it before. It’s a very cheap and easy-to-use VPS Hosting with a price starting at $5 a month.</p><h4>Domain</h4><p>I registered my domain at <a href="https://namecheap.pxf.io/code-curated">Namecheap</a>. Namecheap is a very popular and easy-to-use domain registrar with a competitive price. This is the first time I bought a domain here and I’m recommending it.</p><h4>Content Delivery Network (CDN)</h4><p>I use <a href="https://www.cloudflare.com/">Cloudflare</a>, a very popular and free CDN, on my blog. Using CDN will reduce your site’s response time while also adding its security. I recommend using CDN for every site you have.</p><h4>Business Email (Optional)</h4><p>I use <a href="https://privateemail.com/">Private Email</a> by <a href="https://namecheap.pxf.io/code-curated">Namecheap</a> for my business email. You can buy the account together with a domain in Namecheap. You can also use it as an SMTP client for member sign-in and sign-up, so it’s recommended to have one.</p><h4>Buying Domain on Namecheap</h4><p><a href="https://namecheap.pxf.io/code-curated">Namecheap</a> is a very popular domain registrar with a competitive price. The first thing you need to do to buy a domain on Namecheap is to register.</p><p>After you’re done with the registration, go to the <a href="https://www.namecheap.com/">homepage</a> and type the domain you want to buy in the search bar.</p><figure><img alt="Search domain on Namecheap for Self-Hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*acFVmqYrs7TixzEi.png" /><figcaption>Namecheap domain name search bar</figcaption></figure><p>If the domain name you chose is available, you will see the screen below. In this example, I wanted to buy codecurated.link.</p><figure><img alt="Domain is available for self-host Ghost" src="https://cdn-images-1.medium.com/max/1024/0*P0aFnmor-92KIz_Q.png" /><figcaption>Domain is available</figcaption></figure><p>After you’re done adding the domain to the cart, click “Checkout” at the bottom of the page.</p><figure><img alt="Checkout domain on Namecheap" src="https://cdn-images-1.medium.com/max/1024/0*Y9WatWU_qiKcZ8Kg.png" /><figcaption>Checkout domain on Namecheap</figcaption></figure><p>After that Namecheap will redirect you to checkout page, In this page there are a few things you need to do. I’ll explain it by the numbers I wrote at the picture:</p><figure><img alt="Checkout page on Namecheap for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*2g112D-DjTiNNDmd.png" /><figcaption>Checkout page on Namecheap</figcaption></figure><ol><li>Auto domain renewal. if you turn this on, then Namecheap will automatically renew your domain when it expires.</li><li>Insert your promo code here if you have one.</li><li>Adding email hosting will allow you to use it for business email (e.g. admin@codecurated.com). You can also use the email’s SMTP to send sign-up and sign-in login email for your Ghost blog.</li><li>After you’re set, click “Confirm Order”.</li></ol><p>After that, Namecheap will redirect you to the payment page. Make sure that everything is as you want, after that purchase it. You will receive an email for purchase confirmation if everything went well.</p><p>Congratulations! You’ve bought a domain, this is the first step towards self-hosted Ghost.</p><h4>Setting up Private Email</h4><p>If you bought a Private Email with Namecheap when buying a domain, then you need to set it up.</p><p>To set up the Private Email, first you must to open the account dashboard in Namecheap:</p><figure><img alt="Go to Namecheap dashboard for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*KtDz0i2hp12D8UPH.png" /><figcaption>Go to Namecheap dashboard</figcaption></figure><p>After that, search your domain in the “Recently Active in Your Account Section”, click the arrow as in the image and then go to “Manage”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GyExrbJoM2W5Y4Iq.png" /><figcaption>Manage Private Email</figcaption></figure><p>Since you just registered the Private Email account, you don’t have any mailbox yet. Let’s create a new one by navigating to “Create mailbox now”.</p><figure><img alt="Create mailbox on Namecheap for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*ta8UaM_HpT69K3p2.png" /><figcaption>Create mailbox on Namecheap</figcaption></figure><p>Namecheap will prompt you a pop up as below, fill it with email, password and storage you want. You can change them later by removing and creating a new mailbox. After you’re done, click “Save Changes”.</p><figure><img alt="Create mailbox form on Namecheap for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/784/0*d_CJUsHEEyUFs4Lo.png" /><figcaption>Create mailbox form on Namecheap</figcaption></figure><p>That’s it! You just created your business email! You don’t have to setup the MX in the domain DNS because Namecheap already set it up for you.</p><p>To test it, you can go to <a href="https://privateemail.com/">Private Email site</a> and try logging in with the email and password you provided before.</p><h4>Creating a Ghost Droplet in DigitalOcean</h4><p>For Hosting my Ghost blog, I use <a href="https://m.do.co/c/533434bb8811">DigitalOcean</a>. DigitalOcean is a popular hosting provider with a competitive price. I’ve heard a lot of good things about them and have used them with enjoyable experience for my past projects.</p><h4>Registering on DigitalOcean</h4><p>The first thing you need to do for creating a Ghost Droplet is to register on DigitalOcean if you haven’t.</p><p>After you’ve registered and verified your email, DigitalOcean will ask you to choose the payment method. Choose one you prefer and fill out the form accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*3nlovD77QcUcwxny.png" /><figcaption>Add payment method on DigitalOcean</figcaption></figure><p>If everything went ok, DigitalOcean will redirect you to the page as below, click “Let’s make something”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*Cz60cTTv15vB3IEK.png" /><figcaption>Registration complete on DigitalOcean</figcaption></figure><p>On the next page, DigitalOcean will ask you to configure a droplet. Since we want to create a Ghost droplet and it’s not in the option, just click “Skip this and go to the control panel”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*M1OKWCBk-MyVemJW.png" /><figcaption>Let’s build something on DigitalOcean</figcaption></figure><p>After that, DigitalOcean will redirect you to control panel. The first thing you need to do is go to the “Settings” tab and configure the project name, description and purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bOCHd8zlNgYsbWIm.png" /><figcaption>Configure project on DigitalOcean</figcaption></figure><p>After you’re done, click “Save”.</p><h4>Setting up SSH key (Optional)</h4><p>Since we will need to access the droplet via SSH, we’ll first need to set up an SSH Key. SSH key is a key that will let you connect to the droplet. It’s a security measure to make sure that only a PC with a registered key may access the droplet.</p><p>To set up an SSH key, DigitalOcean already has a <a href="https://www.digitalocean.com/docs/droplets/how-to/connect-with-ssh/">very good documentation in their website</a>.</p><h4>Creating a Droplet</h4><p>To create a droplet, you’ll first need to navigate to Droplets section in the left bar and then click “Create Droplet”.</p><figure><img alt="Create droplet on DigitalOcean for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*4W9cJ9a8eq5dTOXO.png" /><figcaption>Create droplet on DigitalOcean</figcaption></figure><p>After that, DigitalOcean will redirect you to Create Droplets page. Go to Marketplace tab, type Ghost on the search bar, and then click Ghost result.</p><figure><img alt="Create Ghost droplet from DigitalOcean&#39;s marketplace" src="https://cdn-images-1.medium.com/max/1024/0*gF8pIUU3BAVeO_7S.png" /><figcaption>Create Ghost droplet from DigitalOcean’s marketplace</figcaption></figure><p>Now let’s setup our droplet! In this article, I will only write the mandatory setup needed to make your Ghost droplet up and running. You can explore the DigitalOcean’s other features and apply it yourself.</p><figure><img alt="Configure Ghost droplet from DigitalOcean&#39;s marketplace" src="https://cdn-images-1.medium.com/max/1024/0*4Pd8eAqDheWPbek1.png" /><figcaption>Configure Ghost droplet from DigitalOcean’s marketplace</figcaption></figure><p>In the image above, I’ve written some numbers in which I will explain here:</p><ol><li>Droplet type, choose Ghost so DigitalOcean will install everything you need for Ghost when creating the droplet.</li><li>Plan, for starting I recommend just using the cheapest one, it’s enough.</li><li>Data center, choose where your target audience live, if this confuse you then just choose US server.</li><li>Authentication, you need to choose how the droplet will authenticate your account when you do an SSH later on. In this example I chose SSH key, but if you haven’t setup your SSH key, then you can use password instead.</li><li>Your droplet name, you can fill it by anything you want</li><li>Add weekly backup of your droplet, you can also enable this later.</li><li>If you’re already sure with your option, click “Create Droplet”</li></ol><p>If everything went fine, then you should see the droplet under your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9n0qp05P9GuGPufJ.png" /><figcaption>Droplet created in project</figcaption></figure><p>You can validate whether the IP works by visiting it. You should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DATIU-5e9UriiwVL.png" /><figcaption>Log into SSH page</figcaption></figure><p>Nice! Now you have a droplet containing Ghost, as you can see you must log into your droplet via SSH to finish Ghost installation. But let’s come back to it later, for now we’ll setup our CDN first.</p><h4>Setting up Cloudflare CDN to your domain</h4><p>I recommend you to set up a CDN on all your sites. CDN will add a layer of security for your site and also fasten the response time. You can read more about how they do it <a href="https://www.cloudflare.com/learning/cdn/what-is-a-cdn/">here</a>. Cloudflare is a very popular and free to use CDN, for starter I recommend you to use it.</p><h4>Registering on Cloudflare</h4><p>To register on Cloudflare, go to their sign-up <a href="https://dash.cloudflare.com/sign-up">here</a> and fill Email and Password. After that click “Create Account”</p><figure><img alt="Register Cloudflare account for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/600/0*JfLaXFjumZzVCEiC.png" /><figcaption>Register Cloudflare account</figcaption></figure><p>After that Cloudflare will send you an email containing link for verifying your account. Open your email and verify it.</p><h4>Adding our domain to Cloudflare</h4><p>After clicking “Create Account” you’ll also redirected to a new page, insert the domain you’ve bought and click “Add site”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*hB9AZO6fpbeB1YSR.png" /><figcaption>Add your domain to Cloudflare</figcaption></figure><p>Cloudflare will ask you to choose which plan do you want, pick free one and then click “Continue”.</p><figure><img alt="Choose Cloudflare plan for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*FMTjd6bkGafk9NYf.png" /><figcaption>Choose Cloudflare plan</figcaption></figure><p>Cloudflare will prompt your DNS records for your domain, for now you don’t have to do anything, so just click “Continue”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-SoxqgPnNiOK4MqQ.png" /><figcaption>Check DNS record on Cloudflare</figcaption></figure><p>After that Cloudflare will ask you which method do you want for moving your domain to Cloudflare, choose the default one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*74uOK66NGRoQpWXQ.png" /><figcaption>Choose method to move domain to Cloudflare</figcaption></figure><p>They’ll ask you to point your domain nameserver to Cloudflare’s. Write the text in Nameserver 1 and Nameserver 2. In my case it’s kellen.ns.cloudflare.com and magdalena.ns.cloudlfare.com, but yours might be different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*lOOSFERkyUNSdShU.png" /><figcaption>Cloudflare’s nameservers</figcaption></figure><h4>Changing your domain’s nameserver to Cloudflare nameserver</h4><p>The next step is to open Namecheap, open your dashboard, and click “Manage” on the domain you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xgpwg_Cjn6J_Vu3a.png" /><figcaption>Manage domain on Namecheap</figcaption></figure><p>After that go to Nameservers row, change it to “Custom DNS” and add the nameservers you’ve got from Cloudflare. Click the tick mark after you’re done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DW0iP2-3K9XP_ZPr.png" /><figcaption>Change nameservers on Namecheap</figcaption></figure><p>After you’re done go back to Cloudflare and click “Done, check nameservers”.</p><p>Nameservers change might not be instant, so if the verification fails just wait a moment before trying again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*luTNvcGmiwfChsb4.png" /><figcaption>Check nameservers on Cloudflare</figcaption></figure><p>After that, Cloudflare will redirect you to Quick Start page, click “Get Started”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*bGoL6esaItf49Lh6.png" /><figcaption>Cloudflare’s get started</figcaption></figure><p>My recommendation is to turn on Automatic HTTPS Rewrites and Always use HTTPS. You can leave other settings as the default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/0*KyWRCbtcl1NZtofW.png" /><figcaption>Recommended settings for Cloudflare</figcaption></figure><p>If everything went fine, you will see this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nVi2I2V9n9nRmHrJ.png" /><figcaption>Successfully added domain to Cloudflare</figcaption></figure><p>If you still see nameservers setup page, then wait a moment and then click “Recheck now” in the page.</p><h4>Setting your domain in Cloudflare to point to your droplet</h4><p>Now it’s time to point your domain to the droplet you’ve created in the previous section. The first thing you need to do is to open DigitalOcean project dashboard and copy your droplet’s IP.</p><figure><img alt="Copy Ghost droplet&#39;s IP on DigitalOcean" src="https://cdn-images-1.medium.com/max/1024/0*zDoqqpHu786K9Rys.png" /><figcaption>Copy Ghost droplet’s IP on DigitalOcean</figcaption></figure><p>After that, go back to Cloudflare go to the DNS tab and edit a record of type “A” and your domain name.</p><figure><img alt="Edit DNS records on Cloudflare for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*ZTKz6fHmUWh2LYZc.png" /><figcaption>Edit DNS records on Cloudflare</figcaption></figure><p>Paste your droplet’s IP to IPv4 address field and click save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EQRsn_lJGNn-p8LM.png" /><figcaption>Insert IPv4 address in Cloudflare</figcaption></figure><p>You also need to change a DNS record with name “www”. Change the target to your domain name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7mT8m_gXb1QFZMOY.png" /><figcaption>Change www CName</figcaption></figure><p>After you’re done, go to your domain name. You should see this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZNUiqMyZjIUwOxZf.png" /><figcaption>Testing your domain</figcaption></figure><p>Congrats! Now your domain is pointing to your droplet via CDN.</p><h4>Setting up SSL/TLS</h4><p>Before going back to our droplet setup, we must configure one more thing, SSL. You need to configure the SSL in the Cloudflare so it can know that your droplet has a SSL certificate.</p><p>To configure your SSL, go to the SSL/TLS tab and choose Full.</p><figure><img alt="Setting up SSL on Cloudflare for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/1024/0*tVefy4RA0Wbcd05C.png" /><figcaption>Setting up SSL on Cloudflare for self-hosted Ghost</figcaption></figure><p>And you’re done! If you open your website now it might not work, but no worries, it will work again after we’re done with our Ghost installation. Let’s move on to the next step!</p><h4>Configure Ghost installation on DigitalOcean</h4><p>Okay, it’s time to do an SSH to your Ghost droplet. First, copy the IP of your droplet.</p><figure><img alt="Copy Ghost droplet&#39;s IP" src="https://cdn-images-1.medium.com/max/1024/0*FNnQp7EWJmQlnreD.png" /><figcaption>Copy Ghost droplet’s IP</figcaption></figure><p>After that open windows powershell or terminal and type ssh root@{your-droplet-ip}</p><figure><img alt="SSH to Ghost droplet" src="https://cdn-images-1.medium.com/max/1024/0*TgTyOYNpgG4vU8uM.png" /><figcaption>SSH to Ghost droplet</figcaption></figure><p>If you’re warned about authenticity of host, then type yes.</p><figure><img alt="Authenticity of host prompt on Ghost droplet" src="https://cdn-images-1.medium.com/max/1024/0*lJkKkgZtxRxlyY8k.png" /><figcaption>Authenticity of host prompt on Ghost droplet</figcaption></figure><p>If you’re using a password for your droplet’s authentication it might prompt you to input password. If you’re using SSH key, then you should be able to access your droplet inputting nothing.</p><p>The droplet will begin installation automatically and should stop at this screen:</p><figure><img alt="Get started on Ghost droplet" src="https://cdn-images-1.medium.com/max/1024/0*kFi24TCSuwLdeOdW.png" /><figcaption>Get started on Ghost droplet</figcaption></figure><p>Just press enter on your keyboard and it should start the installation process again. After a while it will prompt you to insert your blog URL, insert your domain here.</p><figure><img alt="Enter domain name on Ghost droplet" src="https://cdn-images-1.medium.com/max/1024/0*huo45qjTWEga5_LV.png" /><figcaption>Enter domain name on Ghost droplet</figcaption></figure><p>After that, it will ask you to input your email for SSL certificate. SSL certificate is very important for website security. Having it on your site will also boost your SEO score.</p><figure><img alt="Enter email for SSL certificate on Ghost droplet" src="https://cdn-images-1.medium.com/max/1024/0*FxB_a0xbJwszQus1.png" /><figcaption>Enter email for SSL certificate on Ghost droplet</figcaption></figure><p>When the droplet finishes setting up Ghost, you should see the screen below.</p><figure><img alt="Finish setting up Ghost droplet" src="https://cdn-images-1.medium.com/max/1024/0*oXolSrF-s_jokQDc.png" /><figcaption>Finish setting up Ghost droplet</figcaption></figure><p>Now, you can see Ghost homepage when you open your domain. Congrats!</p><figure><img alt="Self-hosted Ghost homepage" src="https://cdn-images-1.medium.com/max/1024/0*gDFeRy7eCy-4XwvE.png" /><figcaption>Self-hosted Ghost homepage</figcaption></figure><p>To use email feature in Ghost you’ll need to either ask DigitalOcean to allow your droplet to send email or setup SMTP Email for Ghost. I also plan to write about how to configure email to your Ghost droplet, so <a href="https://codecurated.com/#/portal/signup">wait for it</a>.</p><h4>Setting up Ghost Admin</h4><p>To set up admin page you must go to {your-domain}/ghost. Ghost will prompt you the page below, click “Create your account”.</p><figure><img alt="Setting up self-hosted Ghost" src="https://cdn-images-1.medium.com/max/988/0*_iEtum-qe2SziuIG.png" /><figcaption>Setting up self-hosted Ghost</figcaption></figure><p>Fill out the form as you want, we will use this for the admin account of your blog. After you’re done, click “Last step”.</p><figure><img alt="Creating admin account for self-hosted Ghost" src="https://cdn-images-1.medium.com/max/575/0*hkyQxdX03p0krBc3.png" /><figcaption>Creating admin account for self-hosted Ghost</figcaption></figure><p>In this step you can invite your blog’s author/editor/contributor. If you don’t have one, you can do this later.</p><p>Note that if you want to invite staff users you need to set up email on your Ghost droplet.</p><figure><img alt="Invite staff users on self-hosted Ghost" src="https://cdn-images-1.medium.com/max/875/0*SbLKdR1PuPB6TZhP.png" /><figcaption>Invite staff users on self-hosted Ghost</figcaption></figure><p>After that Ghost will take you to your admin page.</p><figure><img alt="Self-hosted Ghost&#39;s admin page" src="https://cdn-images-1.medium.com/max/1024/0*Ym_wuxj9WB5H-4cT.png" /><figcaption>Self-hosted Ghost’s admin page</figcaption></figure><p>Congrats! Now you have your Self-Hosted Ghost fully setup!</p><h4>What’s next</h4><p>Thank you for reading until the end! Now you can set up yourself a Ghost website. There are still many things I want to write about Ghost like setting up google analytics, configuring routes, configuring robots.txt, configuring email and configuring membership. Be sure to subscribe to Code Curated newsletter for other ghost tutorials!</p><p>Previously published at <a href="https://codecurated.com/blog/how-to-set-up-a-self-hosted-ghost-blogging-platform/">codecurated.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b016a35f614" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reasons I Changed From WordPress to Ghost]]></title>
            <link>https://medium.com/swlh/reasons-i-changed-from-wordpress-to-ghost-4232c7dfa81c?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4232c7dfa81c</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[ghosts]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Sat, 21 Nov 2020 07:57:00 GMT</pubDate>
            <atom:updated>2020-11-23T08:31:25.686Z</atom:updated>
            <content:encoded><![CDATA[<h4>Abandoning my 2 months old WordPress blog</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*C8iwKu3xhnQQ5rFG.jpg" /></figure><p>If you know me, you might’ve noticed I created a new blog with Ghost. <a href="https://brilianfird.com/">My old WordPress blog</a> is just 2 months old, it’s still up, but I’m thinking to redirect the traffic from that blog to my <a href="https://codecurated.com/">new Ghost blog</a>.</p><p>If you don’t already know, <a href="https://wordpress.org/">WordPress</a> is a CMS many people use for creating websites and blog. It already exists for a very long time. <a href="https://ghost.org/">Ghost</a>, is a relatively new CMS focused on blogging. It’s not really new since it’s already exists for over 5 years, but its age feels like nothing when compared to WordPress.</p><p>WordPress is really famous for creating a blog. I too have some experience with it from my blog about 10 years ago. When I’m thinking to create a new blog, WordPress is the only CMS that I thought I can create a blog easily of. There are another CMS and platform like Drupal, Joomla, Wix or Squarespace, but I’m not really familiar with them, hence, I used the CMS that I know well, WordPress.</p><p>Around one week after I created my blog, I stumbled upon Ghost CMS. I’ve always thought that WordPress is using outdated language, which is PHP, and I don’t really like that. I don’t think I will ever want to learn PHP. With Ghost, though, the team marketed it as a fast Headless CMS using Javascript. At first, I’m not really interested in making blog with Ghost because I read you can’t really make a platform other than blog with it.</p><p>I tried it–I created a Ghost droplet in DigitalOcean to see how it performs, and I like it very much. I compared the experience I got when I’m using Ghost with when I’m using WordPress, and I like Ghost more. So, I created a new blog with Ghost while also using the opportunity to change my domain name.</p><p>In this article, I’ll write why I used Ghost instead of WordPress. Please note that I won’t write this article as a detailed comparison. I will write my opinion about why I moved my blog into Ghost, so take it with a grain of salt.</p><h3>Ghost uses JavaScript and Node.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nz_i5zt8qcbZHx2V" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a programmer myself, I enjoy learning and developing with more modern language. Ghost’s developers build Ghost on top of Node.js with JavaScript programming language while WordPress developers build WordPress using PHP. Both are pretty old programming language, right? The reason I like JavaScript and Node.js more is that, there are many companies that use them. While with PHP, I haven’t really found a job opening for PHP developers that pays well in my region.</p><p>I’m not really familiar will both language, I’ve tried some JavaScript and PHP, but not really on a professional level. But if you ask me which to learn, then I’d choose JavaScript for sure. By learning JavaScript, I’d also increase my skill that uses to work in my company, while PHP, I can only use it for developing WordPress.</p><h3>It’s fast and doesn’t need a lot of resources</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2aKysfhxFvtCx85c" /><figcaption>Photo by <a href="https://unsplash.com/@jakegivens?utm_source=medium&amp;utm_medium=referral">Jake Givens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The struggle I feel the most with WordPress is its speed. When using WordPress in a cheap hosting, you can feel its slowness for sure. I don’t mean the side that the users see, it’s doesn’t differ much on that side, I mean the admin page.</p><p>I used the cheapest droplet in DigitalOcean to test both of their speed. The difference is very notable. WordPress’ admin page in a cheap droplet feels very slow. Especially when you’re changing pages, writing articles, saving draft, and publishing your post, you can feel that it’s not very responsive and slow.</p><p>With Ghost, though, I’m very impressed. When I tried Ghost after using WordPress, even in a cheap droplet or hosting, I’m still having a delightful experience using it. The admin page is quick and smooth as opposed to WordPress. Changing page, writing articles, saving, and publishing it feels quick. Before using Ghost, I’m not confident that the cheapest droplet would still give a pleasant experience. But, I was wrong, it’s much more fast that I expected, and I like it very much.</p><h3>There is no plugin in Ghost</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d0HD33yD9tqvxeIL" /><figcaption>Photo by <a href="https://unsplash.com/@cbpsc1?utm_source=medium&amp;utm_medium=referral">Clint Patterson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Depending on the use case, no plugins can be an advantage or a disadvantageous. In my case, though, it’s an advantage.</p><p>Plugin seems like a good idea. You can just one click install it and everything will work, and it is a good idea that helps non developer. But I don’t like using plugin, because you don’t know how the plugin really works in the code level unless you go extra miles to read all the plugins’s code. It might clutter and slow down your blog. It might also break another plugin, or worse, just break your blog. Unless you have an experience in developing with the CMS, it’s very complicated to make a good blog with optimized speed.</p><p>With Ghost, though, you can use integration instead of plugin. You’ll need a bit of coding skill to do an integration, which I have, so no problem for me. You must add JavaScript, HTML or CSS by yourself if you want to add integration. Not all the integration needs it, but most of them are.</p><p>With using Integration, I know things will work and won’t clash with each other. It’s harder to apply, and there aren’t many integrations compared to WordPress’s plugins. But, for my use case, I only need a simple blog for now, so I prefer using integration.</p><h3>Clean UI and UX</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EycXCYQ-twk4Au1krYrsIg.jpeg" /><figcaption>Ghost admin page</figcaption></figure><p>Ghost is really beautiful a look at, and it’s also easy to navigate within. The UI and UX of Ghost are superb, especially when compared to the out-of-date UI UX of WordPress. I know that this depends of each person, but I’m pretty confident to say that most people would like Ghost UI UX more.</p><p>When comparing it to WordPress, you surely notice that there aren’t many menus on the Ghost’s admin page. It’s much less cluttered, you usually can find what you want to change easily. There aren’t many settings you can change in Ghost, it only allows you to change the things that you need. When you’re new to blogging with Ghost, it won’t confuse you because there aren’t many settings you need to change. You can just start blogging.</p><h3>The takeaways</h3><p>The points above are the major reasons I changed from using WordPress to Ghost. It suits my use case very well, at least for now. Unlike WordPress, which you can build many types of websites on, you can only build a blog on Ghost. Ghost team makes Ghost specifically for blogging.</p><p>As I wrote in the beginning, this is my very opinion. What you’re seeing might differ from mine. Like, you might prefer developing your blog with WordPress so you can translate your PHP skill for freelancing. I don’t. This articles just contains my thought process when deciding to use Ghost.</p><p>Alas, thank you very much for reading until the end. I have planned to post articles about Ghost, like how do I setup my Self-Hosted Ghost site. If you’re interested, please subscribe to <a href="https://codecurated.com/blog/reasons-i-changed-from-wordpress-to-ghost/#/portal/signup">Code Curated Newsletter</a>.</p><p><em>Originally published at </em><a href="https://codecurated.com/blog/reasons-i-changed-from-wordpress-to-ghost/"><em>https://codecurated.com</em></a><em> on November 21, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4232c7dfa81c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/reasons-i-changed-from-wordpress-to-ghost-4232c7dfa81c">Reasons I Changed From WordPress to Ghost</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Analyzers in Elasticsearch]]></title>
            <link>https://medium.com/better-programming/an-introduction-to-analyzers-in-elasticsearch-9596917693a2?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9596917693a2</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 16:07:35 GMT</pubDate>
            <atom:updated>2020-11-13T16:07:35.678Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the process and components</h4><figure><img alt="Hiker taking in lakeside view" src="https://cdn-images-1.medium.com/max/1024/0*0gDQpYd2FwInEybf" /><figcaption>Photo by <a href="https://unsplash.com/@lucabravo?utm_source=medium&amp;utm_medium=referral">Luca Bravo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>If you want to create a good search engine with <a href="https://www.elastic.co/elasticsearch/">Elasticsearch</a>, knowing how an analyzer works is a must. A good search engine is a search engine that returns relevant results. When the user queries something in our search engine, we need to return the documents relevant to that query.</p><p>One component we can tune so Elasticsearch returns relevant documents is an analyzer. An analyzer is a component responsible for processing the text we want to index and controlling which documents are more relevant when querying.</p><h3>Inverted Index</h3><p>Since analyzers correlate tightly with inverted indexes, we need to understand what an inverted index is first.</p><p>An inverted index is a data structure for storing a mapping between tokens to the document identifiers that have the term. Other than document identifiers, the inverted index also stores the token position relative to the documents. Since Elasticsearch maps the tokens with document identifiers, when you do a query to Elasticsearch, it can easily get the documents you want and return them quickly.</p><h3>Indexing Documents Into Inverted Index</h3><p>Let’s say that we want to index two documents:</p><ul><li>Document 1: “Elasticsearch is fast”</li><li>Document 2: “I want to learn Elasticsearch”</li></ul><p>Let’s take a peek into the inverted index and see the result of the analysis and indexing process:</p><figure><img alt="Table showing analysis and indexing results" src="https://cdn-images-1.medium.com/max/356/0*qDIUgwt463_b65tu.png" /></figure><p>As you can see, the terms are counted and mapped into document identifiers and their position in the document. The reason we don’t see the full document “Elasticsearch is fast” or “I want to learn Elasticsearch” is because they go through the analysis process, which is our main topic in this article.</p><h3>Querying Into Inverted Index</h3><p>There is one thing to note regarding querying to an inverted index: Elasticsearch will only get the documents with the same term as the one queried.</p><p>We can easily test this by using two types of Elasticsearch queries: a match query and term query. Basically, a match query will go through an analysis process, while a term query won’t. If you’re interested in the difference between them, you can read <a href="https://medium.com/better-programming/elasticsearch-text-vs-keyword-2ccb99ec72ae">this article</a>.</p><p>If you try to do the term query “Elasticsearch” to the index in the example above, you won’t get any result. This happens because the token in the inverted index is “elasticsearch” with a lowercase “e.” When you try the same using a match query, Elasticsearch will analyze the query into “elasticsearch” before searching in the inverted index. Hence, the query will return results.</p><h3>What Is Analyzer in Elasticsearch?</h3><p>When we insert a text document into Elasticsearch, it won’t save the text as it is. The text will go through an analysis process performed by an analyzer. In the analysis process, an analyzer will first transform and split the text into tokens before saving it to the inverted index.</p><p>For example, inserting “Let’s build an Autocomplete!” to Elasticsearch will transform the text into four terms: “let’s,” “build,” “an,” and “autocomplete.”</p><figure><img alt="Diagram of analysis process" src="https://cdn-images-1.medium.com/max/480/0*ylGIph81hHBUVrrW.png" /></figure><p>The analyzer will affect how we search the text, but it won’t affect the content of the text itself. With the previous example, if we search for “let”, Elasticsearch will still return the full text “Let’s build an autocomplete!” instead of only “let.”</p><h3>Elasticsearch’s Analyze API</h3><p>Elasticsearch provides a very convenient API that we can use to test and visualize an analyzer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4ca7d87b8deccc31e0eb366a94fa3ca/href">https://medium.com/media/c4ca7d87b8deccc31e0eb366a94fa3ca/href</a></iframe><p>This API will significantly ease our analyzer’s debugging process. We will use it a lot in this article.</p><h3>Analyzer’s Components</h3><p>Elasticsearch’s analyzer has three components you can modify depending on your use case:</p><ul><li>Character filters</li><li>Tokenizer</li><li>Token filters</li></ul><h4>Character filters</h4><p>The first process that happens in the analysis process is character filtering, which removes, adds, and replaces the characters in the text.</p><p>There are three built-in character filters in Elasticsearch:</p><ul><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-htmlstrip-charfilter.html">HTML strip character filters</a>: Will strip out HTML tags and characters like &lt;b&gt;, &lt;i&gt;, &lt;div&gt;, &lt;br /&gt;, etc.</li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-mapping-charfilter.html">Mapping character filters</a>: This filter will let you map a term into another term. For example, if you want to make the user search an emoji, you can map “:)” to “smile.”</li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-pattern-replace-charfilter.html">Pattern replace character filter</a>: Will replace a regular expression pattern into another term. Be careful, though. Using a pattern replace character filter will slow down your document indexing process.</li></ul><h4>Tokenizer</h4><p>After the character filtering process, our text proceeds to the tokenization process with a tokenizer. Tokenization splits your text into tokens. For example, we previously transformed “Let’s build an autocomplete” to “let’s,” “build,” “an,” and “autocomplete.” The transformation process of splitting the text into four tokens is done by a tokenizer.</p><p>There are too many tokenizers to cover in this article. If you’re interested, you can find the list in the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenizers.html">Elasticsearch documentation</a>.</p><p>Some of the most commonly used tokenizers are:</p><ul><li>Standard tokenizer: Elasticsearch’s default tokenizer. It will split the text by whitespace and punctuation.</li><li>Whitespace tokenizer: A tokenizer that splits the text by only whitespace.</li><li>Edge N-Gram tokenizer: Really useful for creating an autocomplete. It will split your text by whitespace and characters in your word (e.g. Hello -&gt; “H,” “He,” “Hel,” “Hell,” “Hello.”).</li></ul><p>Note that you need to be careful with tokenizers because too many would slow down your insert process.</p><h4>Token filters</h4><p>Token filtering is the third and final process in the analysis. This process will transform the tokens depending on the token filter we use. In the token filtering process, we can lowercase, remove stop words, and add synonyms to the terms.</p><p>There are also many token filters in Elasticsearch. You can read about them in <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-tokenfilters.html">the documentation</a>.</p><p>The most common usage of token filters is a lowercase token filter that will lowercase all your tokens.</p><h3>Standard Analyzer</h3><p>A standard analyzer is the default analyzer of Elasticsearch. If you don’t specify any analyzer in the mapping, then your field will use this analyzer. It uses grammar-based tokenization specified in <a href="https://unicode.org/reports/tr29/">Unicode’s Standard Annex #29</a>, and it works pretty well with most languages.</p><p>The standard analyzer uses:</p><ul><li>A standard tokenizer</li><li>A lowercase token filter</li><li>A stop token filter (disabled by default)</li></ul><p>So with those components, it basically does the following:</p><ul><li>Tokenizes the text into tokens by whitespace and punctuation.</li><li>Lowercases the tokens.</li><li>If you enable the stop token filter, it will remove stop words.</li></ul><p>Let’s try explaining the document “Let’s learn about Analyzer!” with a standard analyzer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7545a142eeaec4a7a005eee987aecfdf/href">https://medium.com/media/7545a142eeaec4a7a005eee987aecfdf/href</a></iframe><p>We can see that a standard analyzer splits the text into tokens by whitespace. It also removes the punctuation mark “!” because there is no token after it. We can see that all the tokens are lowercased because the standard analyzer uses a lowercase token filter.</p><p>In <a href="https://medium.com/better-programming/create-a-simple-autocomplete-with-elasticsearch-852c47109deb">my previous article</a>, we only used the standard analyzer and created a simple autocomplete. By using a custom analyzer that contains our chosen character filters, tokenizer, and token filters, we can make a more advanced autocomplete that will produce more relevant results.</p><h3>Custom Analyzer</h3><p>A custom analyzer is an analyzer in which we can define its name and components according to what we want.</p><p>To create a custom analyzer, we have to define it in our Elasticsearch settings, which we can do when creating an index:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55ccae5a7814fda1e90a902f3c104d31/href">https://medium.com/media/55ccae5a7814fda1e90a902f3c104d31/href</a></iframe><p>We just created a custom analyzer with a whitespace tokenizer, html_strip character filter, and lowercase filter. But is there any way to test the analyzer before we use it in our index?</p><p>Let’s try it out using the text &lt;b&gt;Let’s build an autocomplete!&lt;/b&gt; and compare it with a standard analyzer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/655aece310928fb0e88c90c604d372bf/href">https://medium.com/media/655aece310928fb0e88c90c604d372bf/href</a></iframe><p>We can see some differences between them:</p><ol><li>The results of the standard analyzer have two b tokens, while the cust_analyzer does not. This happens because the cust_analyzer strips away the HTML tag completely.</li><li>The standard analyzer splits the text by whitespace or special characters like &lt;, &gt;, and !, while the cust_analyzer only splits the text by whitespace.</li><li>The standard analyzer strips away special characters, while the cust_analyzer does not. We can see the difference in the autocomplete! token.</li></ol><p>So everything is as we expected. Our analyzer behaves how we want it to. Our last step is to apply it to the field by using mapping:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/224c5b37d555cba009767fad17e4386e/href">https://medium.com/media/224c5b37d555cba009767fad17e4386e/href</a></iframe><p>Now, we mapped our standard-text field to use a standard analyzer, and cust_analyzer-text to use a cust_analyzer.</p><p>Let’s index the document &lt;b&gt;Let’s build an autocomplete!&lt;/b&gt; and try it out!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efe9113379d667ab69da4164d935fa67/href">https://medium.com/media/efe9113379d667ab69da4164d935fa67/href</a></iframe><p>Let’s try to query b with bool query and see what happens:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/525dcfaa4c373cfc1344e86f9598ad11/href">https://medium.com/media/525dcfaa4c373cfc1344e86f9598ad11/href</a></iframe><p>The only result is the document we index using a standard analyzer because we didn’t strip the HTML tag with an html_strip character filter in the standard analyzer, while we did in the cust_analyzer.</p><p>Let’s try one more query, autocomplete!:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a6c2d2adade87b032ea47365250cb38/href">https://medium.com/media/4a6c2d2adade87b032ea47365250cb38/href</a></iframe><p>Now, the only result is the document we index using a cust_analyzer. Since the standard analyzer splits the document into tokens by whitespace and punctuation, it removes the ! character. The cust_analyzer only splits the documents by whitespace, so the ! is not removed.</p><h3>Conclusion</h3><p>An analyzer is an important component you need to learn if you want to create a good search engine. Understanding it is the first step to controlling which documents to show to the users when they query words.</p><p>The next step to creating a good search engine is to understand the relevance score calculation, boosting, querying, and features to use, which I intend to write about. Stay tuned.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9596917693a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/an-introduction-to-analyzers-in-elasticsearch-9596917693a2">An Introduction to Analyzers in Elasticsearch</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle Typos in Elasticsearch Using Fuzzy Query]]></title>
            <link>https://medium.com/data-science/how-to-handle-typos-in-elasticsearch-using-fuzzy-query-8d3843a8cff3?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d3843a8cff3</guid>
            <category><![CDATA[autocomplete]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Sat, 10 Oct 2020 06:43:22 GMT</pubDate>
            <atom:updated>2020-10-13T17:58:32.914Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>Improve user’s experience by handling typos easily with Elasticsearch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4x5Z4TKEZcPX9EfO" /><figcaption>Photo by <a href="https://unsplash.com/@dearseymour?utm_source=medium&amp;utm_medium=referral">Ksenia Makagonova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Typo is something that often happens and can reduce user’s experience, fortunately, Elasticsearch can handle it easily with Fuzzy Query.</p><p>Handling typos is a must if you’re building an advanced autocomplete system with the Elasticsearch.</p><p>If you want to create a simple one instead, you can read my other articles “<a href="https://medium.com/better-programming/create-a-simple-autocomplete-with-elasticsearch-852c47109deb">Create a Simple Autocomplete With Elasticsearch</a>”.</p><h3>What is fuzzy logic</h3><p>Fuzzy logic is a mathematics logic in which the truth of variables might be any number between 0 and 1. It is different with a Boolean logic that only has the truth values either 0 or 1.</p><p>In the Elasticsearch, fuzzy query means the terms in the queries don’t have to be the exact match with the terms in the Inverted Index.</p><p>To calculate the distance between query, Elasticsearch uses <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein Distance Algorithm</a>.</p><h3>How to calculate distance using Levenshtein Distance Algorithm</h3><p>Calculating a distance with Levenshtein Distance Algorithm is easy.</p><p>You just need to compare the first and second word character by character.</p><p>If the character is different, then you can add the distance between the words by one.</p><p>Let’s see an example, how to calculate the distance between the common typo word &quot;Gppgle&quot; with the correct word &quot;Google&quot; .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*ZTXaZlcY3de3nuMn" /><figcaption>Elasticsearch Fuzzy Query: Levenshtein Distance</figcaption></figure><p>After we calculate the distance between &quot;Gppgle&quot; and &quot;Google&quot; with Levenshtein Distance Algorithm, we can see that the distance is 2.</p><h3>Fuzzy Query in Elasticsearch</h3><p>Handling typo in Elasticsearch with Fuzzy Query is also simple.</p><p>Let’s start with making an example of the typo word &quot;Gppgle&quot;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ad7e89599a4bccd1a9728ea734ee321/href">https://medium.com/media/3ad7e89599a4bccd1a9728ea734ee321/href</a></iframe><p>When we’re using normal Match Query, the Elasticsearch will analyze the query &quot;gppgle&quot; first before searching it into the Elasticsearch.</p><p>The only term in the inverted index is “google” and it doesn’t match the term &quot;gppgle&quot;. Therefore, the Elasticsearch won&#39;t return any result.</p><p>Now, let’s try Elasticsearch’s fuzzy in Match Query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f8aede06000971162fafc8d7a009eda/href">https://medium.com/media/8f8aede06000971162fafc8d7a009eda/href</a></iframe><p>As you can see, with fuzzy, the Elasticsearch returned a response.</p><p>We’ve learnt in the before that &quot;gppgle&quot; and &quot;google&quot; have the distance of 2.</p><p>In the query, we inserted &quot;fuzziness&quot;:&quot;AUTO&quot; instead of a number. Why is it working?</p><p>Elasticsearch will determine what fuzziness distance is appropriate if we use &quot;AUTO&quot; value in the &quot;fuzziness&quot; field.</p><p>For 6 characters, the Elasticsearch by default will allow 2 edit distance.</p><p>&quot;AUTO&quot; fuzziness is preferable, but you can tune it with an exact number if you want to.</p><p>Now, let’s try with an exact number to prove that &quot;gppgle&quot; and &quot;google&quot; have a distance of 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a3caf61e5d1a5cd2aa6e8127bf3b0ec/href">https://medium.com/media/2a3caf61e5d1a5cd2aa6e8127bf3b0ec/href</a></iframe><p>When we use &quot;fuzziness&quot;:&quot;1&quot;, no result is returned by the Elasticsearch.</p><p>With &quot;fuzziness&quot;:&quot;2&quot;, though, the Elasticsearch returned the document &quot;google&quot;.</p><p>This proves our previous distance calculation of &quot;gppgle&quot; and &quot;google&quot; with Levenshtein Distance Algorithm, in which the result is 2.</p><h3>Two types of a fuzzy query in Elasticsearch</h3><p>In the previous example, we use a fuzzy query as a parameter inside Match Query.</p><p>But there is another way to use the fuzzy feature, Fuzzy Query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14a6714b78883ff82d09b27da21df6b7/href">https://medium.com/media/14a6714b78883ff82d09b27da21df6b7/href</a></iframe><p>Seems to be the same! So, what’s the difference between them?</p><h4>Fuzzy Query</h4><p>Fuzzy Query works like just Term Query, the query to Elasticsearch is not analyzed and used raw to search the Inverted Index.</p><p>For example, let’s index one more document &quot;Hong Kong&quot; .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aa8b44ce8d2819bfca2c193e99c8d9d/href">https://medium.com/media/7aa8b44ce8d2819bfca2c193e99c8d9d/href</a></iframe><p>Let’s look on what terms the analyzer produces with Elasticsearch’s Analyze API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30ce632c705ce9573ee034fb5a2f76ca/href">https://medium.com/media/30ce632c705ce9573ee034fb5a2f76ca/href</a></iframe><p>As you can see, the standard_analyzer produce two terms, &quot;hong&quot; and &quot;kong&quot;.</p><p>If you read my other article “<a href="https://medium.com/better-programming/elasticsearch-text-vs-keyword-2ccb99ec72ae">Elasticsearch: Text vs. Keyword</a>”, you’d know that if we use a term query to search &quot;Hong Kong&quot; then we won&#39;t get any result.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1208aecced8c569aa045b4124edbc9bc/href">https://medium.com/media/1208aecced8c569aa045b4124edbc9bc/href</a></iframe><p>This is because there is no term that has less than 2 edit distance with &quot;Hong Kong&quot; in the Elasticsearch.</p><p>Now, Let’s try Fuzzy Query with &quot;Hpng&quot; .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d928134aba53c0e0f6839d2073767bb6/href">https://medium.com/media/d928134aba53c0e0f6839d2073767bb6/href</a></iframe><p>Term &quot;Hpng&quot; in the query and the term &quot;hong&quot; in the Elasticsearch have a distance of two.</p><p>Remember that the term queried and the term in the inverted index is case-sensitive, the distance “2” comes from the difference between &quot;Hp&quot; and &quot;ho&quot;.</p><h4>Match Query with Fuzziness parameter</h4><p>Match Query with fuzziness parameter is more preferable than Fuzzy Query. The analyzer in the query will analyze your query before searching it into the Inverted Index.</p><p>Let’s try the same query as we did in the Fuzzy Query’s section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/625e8f9fb455b21c95aa1473ed2c996f/href">https://medium.com/media/625e8f9fb455b21c95aa1473ed2c996f/href</a></iframe><p>As expected, both queries returned a result!</p><p>The first query, &quot;Hpng Kong&quot; is analyzed into &quot;hpng&quot; and &quot;kong&quot;. Both terms &quot;hpng&quot; and &quot;kong&quot; exist in the Inverted Index.</p><p>&quot;hpng&quot; and &quot;hong&quot; matched with a distance of 1. While &quot;kong&quot; and &quot;kong&quot; match perfectly.</p><p>One thing to note if you plan to use Match Query is that every of the terms in the query will allow fuzziness.</p><p>We can try querying with &quot;hggg kggg&quot; which has an edit distance of 4 with &quot;Hong Kong&quot; using &quot;fuzziness&quot;:2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1fd9dc2dd8e2aa280db3219669f22cf/href">https://medium.com/media/b1fd9dc2dd8e2aa280db3219669f22cf/href</a></iframe><p>As you can see, the Elasticsearch returned a result.</p><p>This is because of the query &quot;hggg kggg&quot; is analyzed to terms &quot;hggg&quot; and &quot;kggg&quot; by the analyzer.</p><p>Both &quot;hggg&quot; and &quot;kggg&quot; respectively have the edit distance of 2 to &quot;hong&quot; and &quot;kong&quot; in the Elasticsearch.</p><h3>Tuning the Fuzzy Query in Elasticsearch</h3><p>You can tune the Fuzzy Query to match your use case.</p><p>In this section, I will write about the parameters that we can change in the query.</p><h4>Fuzziness</h4><p>Fuzziness is the heart of Fuzzy Query.</p><p>The value that we pass to this parameter is the maximum distance allowed.</p><p>There are two types of value that we can pass, an integer for exact maximum distance and &quot;AUTO&quot;.</p><p>The &quot;AUTO&quot; value allows the fuzziness in the query to be dynamic.</p><p>We can tune 2 parameters in the &quot;AUTO&quot; value and write it as &quot;AUTO:[low],[high]&quot;. The query will set fuzziness as 0 if the term length is below the low value. If the term length is between the low and high value, the query will set the fuzziness to 1. Last, If the term length is more than the high value, the query will set the fuzziness to 2.</p><p>The Elasticsearch will use 3 and 6 as the default if the low and high value is not determined.</p><p>Let’s use an example with a document “Fuzzy Query in Elasticsearch allows you to handle typos”.</p><p>We can try some queries to prove the mechanism of AUTO we described earlier.</p><ul><li>“tp”: 1 edit distance from “to”.</li><li>“Fyzzy”: 1 edit distance from “Fuzzy”.</li><li>“Fyzyy”: 2 edit distance from “Fuzzy”.</li><li>“Elastissearcc”: 2 edit distance from “Fuzzy”.</li><li>“Elestissearcc”: 3 edit distance from “Fuzzy”.</li></ul><p>After querying it, these queries produced a result:</p><ul><li>“Fyzzy”</li><li>“Elastissearcc”</li></ul><p>The queries don’t:</p><ul><li>“tp”</li><li>“Fyzyy”</li><li>“Elestissearcc”</li></ul><h4>Transpositions</h4><p>transpositions will allow your query to calculate the transpositions of two adjacent characters (ab -&gt; ba) as 1 distance.</p><p>For example, if we set the transpositions to true, we will get a result if we query with &quot;leasticsearcc&quot;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afb2efae1846393f3b685c9ada61b071/href">https://medium.com/media/afb2efae1846393f3b685c9ada61b071/href</a></iframe><p>But if we set it as false, there will be no result from the Elasticsearch.</p><p>The Elasticsearch defaults the transpositions setting to true.</p><p>We can’t set this setting to the Match Query. The Match Query will always calculate transpositions as 1 distance.</p><h4>Max Expansions</h4><p>max_expansions will determine the maximum result you get from your query.</p><p>If you set the max_expansions to 1 and there is 2 document in the Elasticsearch that are appropriate to your query, the Elasticsearch will only return 1.</p><p>Note that max_expansions applies to shard level. So if you have many shards in the Elasticsearch, even if you set the max_expansion to 1, the query might return more results.</p><p>The default value for max_expansions is 50.</p><h4>Prefix Length</h4><p>prefix_length is the number of prefix characters that is not considered in fuzzy query.</p><p>For example, if we set the prefix_length to 1, we won&#39;t get any result if we query &quot;llasticsearch&quot;.</p><p>The prefix_length setting defaults to 0.</p><h4>Rewrite</h4><p>You can change rewrite parameter if you want to change the scoring of the results.</p><p>You can find more information about the rewrite parameter in the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-term-rewrite.html">Elasticsearch documentation</a>.</p><h3>Conclusion</h3><p>Handling a typo in Elasticsearch is very easy and can improve the user’s experience.</p><p>The simplest way to handle a typo is to just add &quot;fuzziness&quot;:&quot;AUTO&quot; in your Match Query.</p><p>If you want to tune the Query, there are some parameters that you can change with the &quot;fuzziness&quot; being the most important.</p><p>Thank you for reading until the end!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d3843a8cff3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-handle-typos-in-elasticsearch-using-fuzzy-query-8d3843a8cff3">How to Handle Typos in Elasticsearch Using Fuzzy Query</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[Avoiding the Null Pointer Exception With Optional in Java]]></title>
            <link>https://medium.com/better-programming/avoiding-the-null-pointer-exception-with-optional-in-java-96cd75d9b058?source=rss-c5d888ffc5e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/96cd75d9b058</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Brilian Firdaus]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 15:23:35 GMT</pubDate>
            <atom:updated>2020-10-06T15:23:35.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to avoid the “billion-dollar mistake” in Java</h4><figure><img alt="Ladybug standing on tall grass with the sun peeking through." src="https://cdn-images-1.medium.com/max/1024/0*FhehvJo66GN56Wll" /><figcaption>Photo by <a href="https://unsplash.com/@barnabas_1?utm_source=medium&amp;utm_medium=referral">Barnabas Hertelendy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>In 1964, British computer scientist Tony Hoare invented the Null Pointer References.</p><p>The Null Pointer Exception has contributed the most bugs in production exceptions. It was implemented in many programming languages, including C, C++, C#, JavaScript, Java, and more.</p><p>The loss of financial resources, time, and human resources to fix it prompted Hoare to call it a “<a href="https://qconlondon.com/london-2009/qconlondon.com/london-2009/speaker/Tony+Hoare.html">billion-dollar mistake</a>.”</p><p>Java is one of the programming languages that implement Null Pointer References. If you’ve been developing with Java, I’m sure that you’ve seen them a lot. It doesn’t matter if you are new to Java or have ten years of experience. There is always a chance that you’ll encounter a Null Pointer Exception bug.</p><h3>Optional in Java</h3><p>Optional is an API that was introduced in Java 8. If used right, it can solve the problem of the Null Pointer Exception.</p><p>The Optional API implements functional programming and uses a functional interface. If you want to know more about functional programming in Java, you can read my other article, <a href="https://medium.com/better-programming/functional-programming-in-java-explained-ae396e9e516f">Functional Programming in Java, Explained</a>.</p><p>Before we proceed any further, please note that I’m using Java 11 for the examples in this article. If you’re using a different version of Java, some methods might not exist or behave exactly the same.</p><h3>Empty Optional</h3><p>An empty optional is the main way to avoid the Null Pointer Exception when using the Optional API.</p><p>In Optional’s flow, a null will be transformed into an empty Optional. The empty Optional won’t be processed any further. This is how we can avoid a NullPointerException when using Optional.</p><p>We will learn further about how an empty Optional behaves later in this article.</p><h3>Creating an Optional Object</h3><p>There are three ways to initiate an Optional object:</p><ul><li>Optional.of(T)</li><li>Optional.ofNullable(T)</li><li>Optional.empty()</li></ul><h4>Optional.of</h4><p>Optional.of accepts any type with a non-nullable value in its parameter. To create an Optional object with Optional.of, we just have to pass a value in its parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5ebf60f59bb2cda479e797d349db929/href">https://medium.com/media/c5ebf60f59bb2cda479e797d349db929/href</a></iframe><p>Be very careful when you are passing a value to the Optional.of. Remember that Optional.of doesn’t accept null values in its parameter. If you try to pass a null value, it will produce a NullPointerException.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56058521e0cd8fc0f093eea043995860/href">https://medium.com/media/56058521e0cd8fc0f093eea043995860/href</a></iframe><h4>Optional.ofNullable</h4><p>Optional.ofNullable is similar to Optional.of. It accepts any type. The difference is, with Optional.ofNullable, you can pass a null value to its parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47a7f67b4cf28ca5ebb43dfacff022f2/href">https://medium.com/media/47a7f67b4cf28ca5ebb43dfacff022f2/href</a></iframe><p>When Optional.ofNullable is initialized using a null object, it will return an empty Optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a5a8999572f63ddf53dc68143dd926/href">https://medium.com/media/06a5a8999572f63ddf53dc68143dd926/href</a></iframe><h4>Optional.empty</h4><p>An empty Optional can be initialized by using Optional.empty().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc911f3776d9eb525ca703a140f5a274/href">https://medium.com/media/fc911f3776d9eb525ca703a140f5a274/href</a></iframe><h3>Accessing an Optional</h3><p>There are some ways to get the value of an Optional.</p><h4>get</h4><p>A pretty straightforward method. The get method will return the value of Optional if it is present and throw a NoSuchElementException if the value doesn’t exist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9314a9f52c18f428669a78c1387c01a1/href">https://medium.com/media/9314a9f52c18f428669a78c1387c01a1/href</a></iframe><h4>orElse</h4><p>If you want to use a default value if the Optional is empty, you can usethe orElse method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c57bf902b23d9ff777730dda3fdad1/href">https://medium.com/media/32c57bf902b23d9ff777730dda3fdad1/href</a></iframe><h4>orElseGet</h4><p>orElseGet is very similar to the orElse method. It’s just that orElseGet accepts Supplier&lt;T&gt; as its parameter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e8097c5c5e249b495c862740db95023/href">https://medium.com/media/1e8097c5c5e249b495c862740db95023/href</a></iframe><h4>orElseThrow</h4><p>orElseThrow will return the value of the Optional or throw an exception if the value of the Optional is empty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c348fb384792bd08b0abab67ffe3386b/href">https://medium.com/media/c348fb384792bd08b0abab67ffe3386b/href</a></iframe><h3>Processing an Optional</h3><p>There are many ways to process and transform an Optional. In this section, we will learn the common methods that are used.</p><p>As I wrote at the beginning of the article, an empty Optional won’t be processed in the flow. We can see that from the examples in this section.</p><h4>map</h4><p>map is the most used method when processing an Optional object. It accepts Function&lt;? super T, ? extends U&gt; as its parameter and returns an Optional&lt;U&gt;. This means you can use a Function with any type of parameter and the return value will be wrapped to Optional in the map method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdeda721b43e6398c0cc8e5b9f975ce4/href">https://medium.com/media/cdeda721b43e6398c0cc8e5b9f975ce4/href</a></iframe><p>If you try to return a null value in Function&lt;? super T, ? extends U&gt;, the map method will return an empty Optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6208a1ab248e5d3aeda78a8191050d0/href">https://medium.com/media/f6208a1ab248e5d3aeda78a8191050d0/href</a></iframe><p>An empty optional won’t be processed by map. We can confirm this with the following test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e7824e3e5cf38e4add31402abc7f0c6/href">https://medium.com/media/1e7824e3e5cf38e4add31402abc7f0c6/href</a></iframe><h4>flatMap</h4><p>This is similar to map, but flatMap won’t wrap the return value of the Function to Optional. The flatMap method accepts Function&lt;? super T, ? extends Optional&lt;? extends U&gt;&gt; as its parameter. This means that you’ll need to define a Function that accepts any type and returns an Optional.</p><p>You will usually use the flatMap method when your code calls another method that returns an Optional object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99bb26cd5a15ed0eb4767b86ee701cf7/href">https://medium.com/media/99bb26cd5a15ed0eb4767b86ee701cf7/href</a></iframe><h4>filter</h4><p>In the previous example of flatMap, we used a declarative style to differentiate the return value of the getString method. But we can actually use a functional style for that with the filter method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5edab138042de5c53015f2dfb8ee2147/href">https://medium.com/media/5edab138042de5c53015f2dfb8ee2147/href</a></iframe><h4>ifPresent</h4><p>The ifPresent method accepts a Consumer that will only be executed if the Optional is not empty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1776bd601aa2740e0a12eab7d99ac1e/href">https://medium.com/media/e1776bd601aa2740e0a12eab7d99ac1e/href</a></iframe><h3>Things to Avoid</h3><p>There are some critical things that you need to avoid if you want to use Optional in your code.</p><h4>Don’t create a method that accepts Optional</h4><p>Creating a method that accepts Optional as a parameter might introduce a problem it wants to solve, NullPointerException.</p><p>If a person using the method with the Optional parameter is not aware of it, they might pass a null to the method instead of Optional.empty(). Processing a null will produce a NullPointerException.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff73c1e0e28fba25ebfc3ee1da2174bd/href">https://medium.com/media/ff73c1e0e28fba25ebfc3ee1da2174bd/href</a></iframe><h4>Getting value without checking</h4><p>If you’re using Optional, then you should avoid using the get method if you can. If you still want to use it for some reason, make sure that you check it with the isPresent method first because if you use get on an empty Optional, it will produce a NoSuchMethodException.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3b1a4e6d5dc11a70a550bfc1c977b19/href">https://medium.com/media/d3b1a4e6d5dc11a70a550bfc1c977b19/href</a></iframe><h3>Conclusion</h3><p>Thank you for reading until the end! Optional is a powerful feature that every Java developer should know about. If you use optional features from end to end correctly, then I’m sure that you won’t meet the NullPointerException anymore.</p><p>Optional is also used as a base for other big libraries like <a href="https://projectreactor.io/">Reactor </a>and <a href="https://github.com/ReactiveX/RxJava">RXJava</a>, so knowing how Optional works will help you understand them too.</p><p>You can find the repository with the examples in this article below:</p><p><a href="https://github.com/brilianfird/java-optional">brilianfird/java-optional</a></p><h3>References</h3><ol><li><a href="https://medium.com/@hinchman_amanda/null-pointer-references-the-billion-dollar-mistake-1e616534d485">Null Pointer References: The Billion Dollar Mistake</a></li><li><a href="https://en.wikipedia.org/wiki/Tony_Hoare#Apologies_and_retractions">https://en.wikipedia.org/wiki/Tony_Hoare#Apologies_and_retractions</a></li><li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html">https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96cd75d9b058" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/avoiding-the-null-pointer-exception-with-optional-in-java-96cd75d9b058">Avoiding the Null Pointer Exception With Optional in Java</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>