<?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 Victor S Melo on Medium]]></title>
        <description><![CDATA[Stories by Victor S Melo on Medium]]></description>
        <link>https://medium.com/@victorsmelopoa?source=rss-e59cd5367489------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YTKltb2jFVgjx5wBTFYHdQ.jpeg</url>
            <title>Stories by Victor S Melo on Medium</title>
            <link>https://medium.com/@victorsmelopoa?source=rss-e59cd5367489------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:14:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@victorsmelopoa/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[Work Log: implementing Ruby on Rails Cookies Storage]]></title>
            <link>https://medium.com/@victorsmelopoa/implementing-ruby-on-rails-cookies-storage-b0207c148bea?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0207c148bea</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Sun, 07 May 2023 13:23:09 GMT</pubDate>
            <atom:updated>2023-05-07T13:36:21.708Z</atom:updated>
            <content:encoded><![CDATA[<p>I got interested on understanding how Ruby on Rails handles browser cookies. I decided then to develop a simple project to use cookies to store data.</p><p>Here I&#39;ll write my thinking process during the development of that project.</p><p>I will follow the MVC architecture (as it&#39;s default for Rails), with only one controller, one view and one model. It shouldn&#39;t be hard.</p><p>Now I need to remember how to create a new Rails project. In <a href="https://guides.rubyonrails.org/getting_started.html">Rails documentation</a> it&#39;s said I should double check my system has Ruby and SQLite3 installed. Not sure why Rails use SQLite3. Maybe it&#39;s the default database it uses for its model, as I know Rails maps the defined models to database data, something that in some other languages/frameworks we would have to define it manually (DAO, DTO).</p><p>Quickly researching here, I found SQLite3 is needed because it&#39;s a built-in support provided by Rails. Anyway, I don&#39;t intend to use it for this project.</p><p>Ok, I&#39;ve both Rails and SQLite3 installed. To start the new Rails application, I need to run rails new app_name. I will call this project <strong>SimpleCookieStorage</strong>. My next step is to create a Github repository for that.</p><p>Ok, I created the <a href="https://github.com/vctrsmelo/SimpleCookieStorage">Github project</a>, and installed RVM to install a new Ruby version. RVM is probably not necessary for this project, but as I was finding issues with my current installed Ruby version, I decided to use it just to create a &quot;safe&quot; environment to make changes and not impact the MacOS Ruby version installed.</p><p>Ok, I kind of got in a flow state and forgot to update here. I created the simple version of the project. In the end I didn&#39;t use any model as cookies is an available hash in Rails, so my controller modifies it directly. If in the future I want to add an extra layer so the controller is unaware what&#39;s the database being used, I would have this model layer. For now, it&#39;s all good.</p><p>I didn&#39;t add any CSS, as it was not the goal here, but I liked how the result was easy to implement. It was just a matter of creating the HTML (using .html.erb format), defining the routes and implementing the controller to get the result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*AsbY9sIRy1lXZ7ORF0GeIA.gif" /></figure><p>The code is available in my Github: <a href="https://github.com/vctrsmelo/SimpleCookieStorage">https://github.com/vctrsmelo/SimpleCookieStorage</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0207c148bea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time is Money Calculator: release 1.1]]></title>
            <link>https://medium.com/@victorsmelopoa/time-is-money-calculator-release-1-1-ee8d83d0ff50?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee8d83d0ff50</guid>
            <category><![CDATA[indie]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[português]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Mon, 03 Feb 2020 02:26:47 GMT</pubDate>
            <atom:updated>2020-02-03T02:34:41.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Sim! Quero usar este espaço pra divulgar as melhorias feitas no meu app durante este final de semana, e deixar meu agradecimento a todos que me ajudaram.</p><h4><strong>Contexto</strong></h4><p>o app <a href="https://apps.apple.com/us/app/time-is-money-calculator/id1495915563?ign-mpt=uo%3D2">Time is Money</a>, meu primeiro projeto indie, converte valor monetário (preço de roupa, celular, livros ou qualquer produto que o usuário deseje comprar) em tempo de trabalho, de maneira totalmente personalizada.</p><h4><strong>Problemas reportados</strong></h4><ol><li>iPhone SE, 7 e 8 estavam com alguns textos cortados, aparecendo incompletamente.</li></ol><p>2. No iPhone 8 o botão de inserir valor estava grudado em baixo.</p><p>3. No cálculo de tempo, se o período era muito longo (como 10 anos), ao alterar as horas de trabalho semanais, este resultado mudava.</p><p>4. No cálculo de tempo, se o tempo total ultrapassasse 60 anos aproximadamente, o resultado aparecia negativo.</p><p>5. No cálculo de tempo, dois valores monetários inseridos (digamos, R$500 e R$600) resultavam no mesmo período de tempo.</p><h4>Resoluções</h4><p><strong>1. Phone SE, 7 e 8 estavam com alguns textos cortados, aparecendo incompletamente.</strong></p><p>O aplicativo foi desenvolvido usando SwiftUI, até como um desafio pessoal. Por conta disso, problemas de layout eram esperados, e muitos foram tratados antes da submissão para a app store. Infelizmente algumas coisas escapam, e essa foi uma delas. Como SwiftUI ainda é muito novo, às vezes é difícil saber o que foi erro meu e o que é comportamento da biblioteca. Neste caso, para solucionar o problema tive que usar diferentes abordagens em contextos diferentes:</p><ul><li>Apliquei um ViewModifier .lineLimit(nil).</li><li>Usei abordagem baseada <a href="https://stackoverflow.com/questions/57035746/how-to-scale-text-to-fit-parent-view-with-swiftui">neste</a> código para escalar o texto.</li></ul><p><strong>2. No iPhone 8 o botão de inserir valor estava grudado em baixo.</strong></p><p>O botão de inserir valor estava arredondado, seguindo guideline de design dos iPhones com notch. Mas isso não combina com os iPhones que tem botão home. Consegui resolver isso apenas mudando o estilo do botão de acordo com o aparelho dele, detectando se tem notch ou não.</p><p><strong>3. No cálculo de tempo, se o período resultante era muito longo, ao alterar tempo de trabalho semanal, o resultado variava.</strong></p><p>O problema é que o cálculo era baseado apenas num <em>salário por segundo</em> (calculado a partir do salário mensal). Porém, se eu recebo R$1.000 por mês, eu espero que se eu inserir R$1.000 no app, o resultado seja um mês. Mas pelo fato do cálculo estar sendo feito somente sobre este <em>salário por segundo</em>, este resultado variava. Após implementar diversos testes no código, revisar e reimplementar um novo algoritmo para o cálculo, este problema não ocorre mais.</p><p><strong>4. No cálculo de tempo, se o tempo total ultrapassasse 60 anos aproximadamente, o resultado aparecia negativo.</strong></p><p>Esse é interessante. Uso um formatador chamada DateComponentFormatter que converte período de tempo em texto, para ser apresentado. Assim, eu chamava uma função DateComponentFormatter.string(from: timeInterval) para fazer a conversão. Porém, esta função internamente usa uma estrutura de dados Int32, e por isso o valor do limite superior era tão baixo, causando <em>overflow</em>. Chamando outra função ao invés dessa, o problema foi solucionado.</p><p><strong>5. No cálculo de tempo, dois valores monetários inseridos (digamos, R$500 e R$600) resultavam no mesmo período de tempo.</strong></p><p>Isso era resultado de arredondamentos feitos no algoritmo antigo. O algoritmo estava com problemas por conta de usar Double para seus cálculos, mas após pesquisar na internet uma estrutura melhor, vi que para cálculos em base decimal é sugerido usar NSDecimalNumber. Assim, após trocar as estruturas, pude melhorar e muito a precisão do algoritmo. Agora o aplicativo pode executar cálculos com precisão máxima (até que se prove o contrário haha).</p><h4>Conclusão e Agradecimentos</h4><p>No mais foi isso. Neste momento a versão 1.1 do app foi pra revisão da Apple, e quero deixar meus mais sinceros agradecimentos a todas pessoas que demonstraram apoio no LinkedIn, <a href="https://www.linkedin.com/feed/update/urn:li:activity:6629055480411025408/">nesta</a> postagem que fiz lá. Não esperava todo esse suporte, e esperava menos ainda que alguém comprasse o aplicativo pra me apoiar. Sempre fui um terrível vendedor, e me sinto um tanto sozinho quando tento fazer coisas assim, e todas as mensagens lá me encheram de alegria e me fizeram me sentir muito mais motivado pra entregar um produto incrível pra todos que compraram (e que vão comprar) o aplicativo.</p><p>Fica aqui também um agradecimento imenso à todos que reportaram os problemas no aplicativo (seja pessoalmente ou pelo LinkedIn). Vocês me ajudaram muito 🙏.</p><p>E por fim um agradecimento à minha namorada, Débora, que vai me perdoar (espero) por ter ficado o fim de semana inteiro na frente do computador hahaha.</p><p>Valeu gente!</p><p>Se quiser conhecer Time is Money, acesse o link abaixo:</p><p><a href="https://apps.apple.com/us/app/time-is-money-calculator/id1495915563?ign-mpt=uo%3D2">https://apps.apple.com/us/app/time-is-money-calculator/id1495915563?ign-mpt=uo%3D2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee8d83d0ff50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The why I became an indie developer and about my first app]]></title>
            <link>https://medium.com/@victorsmelopoa/the-why-i-became-an-indie-developer-and-about-my-first-app-d5e350a0931c?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5e350a0931c</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[indie]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Mon, 03 Feb 2020 01:31:50 GMT</pubDate>
            <atom:updated>2020-02-03T01:37:05.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrIhNC0D8Pn0k_2zD302cw.png" /><figcaption>Time is Money Calculator: my first indie app</figcaption></figure><p>Yes, 2020 just started and I finally decided to become an indie developer.</p><p>Despite working at ThoughtWorks, an amazing company that I love the culture and the learning environment, and despite I’m still pursuing my computer science degree (hopefully next year I will get it), I decided I should become an indie developer.</p><p>I love programming since I was in high school. At that time, knowing nothing about programming logic, I created a Grand Theft Auto San Andreas multiplier server, programming a wholly online environment based on copying and pasting code. I felt in love with it. It was the place I found to explore my creativity that was repressed in school.</p><p>After high school, I studied design for a year. During that time, I learned a lot about graphical design, user experience, web design, and marketing. Still, I missed the sensation of giving life to something, like I used to do in high school.</p><blockquote>I am one of those people who believe programming is a superpower, and I want to do something great with my superpower.</blockquote><p>Then I decided to pursue a computer science degree and realized that it is what I want to do for life.</p><p>This whole story is to explain how my life was a mix of programming, design, and creativity. I love it when I can merge them into projects I truly believe. I am one of those people who believe programming is a superpower, and I want to do something great with my superpower. And that ambition is what made me realize I want to develop projects as a whole. Projects that I can ideate, projects that I can design, projects that I can code, projects that I can learn a lot. And most of all projects that I really believe will impact positively the lives of people, turning this world, even if just a little, a better place.</p><blockquote>I want to work on projects that I really believe will impact positively the lives of people, turning this world, even if just a little, a better place.</blockquote><h3>Time is Money Calculator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*945Zrh0NpOGo7K_IEVAVCw.png" /><figcaption>Desk representing amount of work, used in the app</figcaption></figure><p>Yes, this is my first project. After six months of working on it, I finally took the courage to release it. I am a person who thinks something is never good enough, and it was really hard for me to release it now, but if I didn’t do It now,I know It would never be good enough.</p><p>After working about a year and a half in a fintech in Brazil, I saw how people worry about money and how they may be wrong about its true value.</p><p>Money is not a piece of paper, it is not a magical element that we use to trade for anything we want. Money is your work.</p><p>Every second you spend working, you are translating moments of your life, moments you could spend with your family or friends, moments that will never come back, for money. Thinking that makes us realize how we are handling our time.</p><p>That is where Time is Money Calculator comes. I developed a tool to translate every monetary value around the world into seconds of your life. It tells you how many seconds, minutes, hours, days, weeks, months or even years of your life will take to pay for something.</p><p>It is a great tool to make you percept how you are spending your life. My goal is not that you stop spending your money in leisure, but it is to give a real dimension about how much anything costs for you. It is a tool to combat the manipulation that marketing campaigns want.</p><p>Here in Brazil, there are so many people indebted that it is a national issue. I believe that part of the cause of this is the wish to have something that you make you happy: a new car, a new cellphone, new clothes or anything else. This is the manipulation I mentioned before.</p><p>For now, that&#39;s all. If you want to know more about this project, be my guest to take a look at it on the<a href="https://apps.apple.com/us/app/time-is-money-calculator/id1495915563?ign-mpt=uo%3D2"> App Store</a>. I really would like to know your opinion and suggestions you may have about it.</p><p><a href="https://apps.apple.com/us/app/time-is-money-calculator/id1495915563?ign-mpt=uo%3D2">https://apps.apple.com/us/app/time-is-money-calculator/id1495915563?ign-mpt=uo%3D2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5e350a0931c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Código Limpo: destaques do capítulo 2]]></title>
            <link>https://medium.com/@victorsmelopoa/c%C3%B3digo-limpo-destaques-do-cap%C3%ADtulo-2-ad1eb7557e6a?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad1eb7557e6a</guid>
            <category><![CDATA[código-limpo]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[uncle-bob]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Wed, 11 Dec 2019 18:51:55 GMT</pubDate>
            <atom:updated>2019-12-12T22:19:22.434Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuando a série de destaques da leitura do livro <em>Código Limpo</em>, do Robert C. Martin.</p><p><a href="https://medium.com/@victorsmelopoa/c%C3%B3digo-limpo-destaques-do-cap%C3%ADtulo-1-ade32203d560">Destaques do capítulo 1</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EGTJK38pL_40wA17BVAPjg.jpeg" /></figure><p>Nomes estão em todos lugares em software: variáveis, funções, argumentos, classes, pacotes, etc. Como criamos nomes o tempo inteiro, queremos criar bons nomes. Neste capítulo são apresentadas regras para isso.</p><h4>Revele a Intenção no Próprio Nome</h4><p>Escolher bons nomes leva tempo, mas salva mais tempo do que gasta. Não há problema em mudar um nome quando encontrar outro melhor, já que melhorar a clareza do código é uma de suas principais funções. <strong>O contexto do nome deve estar no código: não devemos ter que procurar a declaração de uma variável para entendê-la.</strong></p><p>Um nome deve responder:</p><ul><li>Porque este elemento existe.</li><li>O que este elemento faz.</li><li>Como usar este elemento.</li></ul><p>Se um nome requer um comentário, então o nome não revela sua intenção. Por exemplo, considere o código abaixo:</p><pre>int d; // elapsed time in days</pre><p>o nome d não revela nada. Um nome infinitamente melhor seria:</p><pre>int elapsedTimeInDays;</pre><p>Um princípio interessante de lembrar nesse momento: <strong>é melhor ter um código claro do que um código conciso</strong>. No final das contas, escrevemos código para outras pessoas, não para máquinas.</p><p>Outros exemplos de nomes informativos são:</p><pre>int daysSinceCreation;<br>int daysSinceModification;<br>int fileAgeInDays;</pre><p>Uma ideia bem interessante é usar constantes, aliases ou até enum para o contexto ficar mais claro. Por exemplo, ao invés de:</p><pre>if (client.type == 1) {</pre><pre>    enablePremiumFeatures()<br>}</pre><p>Podemos usar um enum e ter:</p><pre>if (client.type == .premium) {</pre><pre>    enablePremiumFeatures()<br>}</pre><h4>Evite Desinformação</h4><p>Não defina um nome que deixe uma pista falsa sobre o que ele representa. Por exemplo, não nomeie um conjunto de contas como accountList a não ser que realmente seja uma lista.</p><p>Também tome cuidado com nomes muito similares, pois eles tendem a causar confusão. Veja o exemplo de duas classes abaixo:</p><pre>XYZControllerForEfficientHandlingOfStrings<br>XYZControllerForEfficientStorageOfStrings</pre><p>É difícil identificar a diferença entre eles. Este tipo de situação também causa problemas em IDEs onde costumamos digitar só o início da classe e recebemos um <em>autocomplete</em>, que pode acabar sugerindo o elemento errado.</p><p>Um exemplo interessante de desinformação é em relação à letra <em>L</em> minúscula ou a letra <em>o </em>maiúscula, que dependendo da fonte usada na IDE, pode nos fazer confundir com <em>i</em> maiúsculo ou com o número <em>0</em>.</p><h4>Faça Distinções Significativas</h4><p>Programadores criam problemas para si mesmos quando escrevem código apenas para o compilador ou interpretador. Nomes como a1, a2,…, an não provêem informação alguma ao programador. Por exemplo, ao invés de:</p><pre>public static void copyChars(char a1[], char a2[]) { ... }</pre><p>Podemos usar:</p><pre>public static void copyChars(char source[], char destination[]) { ... }</pre><p>Lembre-se: <strong>clareza é melhor que concisão</strong>.</p><p>Evite também palavras que só adicionam ruído ao nome. Por exemplo: se você tiver uma classe Product e tiver outra chamada ProductInfo ou<strong><em> </em></strong><em>ProductData</em>, você criou nomes diferentes mas não deixou claro a diferença em seus significados. Info e Data são palavras que só adicionam ruído.</p><p>Outros nomes com ruído podem ser vistos abaixo:</p><pre>var aClient;<br>var theStudent;<br>var professorVariable;<br>var clientNameString;</pre><p>Estes nomes deveriam ser:</p><pre>var client;<br>var student;<br>var professor;<br>var clientName;</pre><p>Um exemplo problemático em métodos é:</p><pre>getActiveAccount();<br>getActiveAccounts();<br>getActiveAccountInfo();</pre><p>Não é possível entender a distinção exata entre os métodos sem procurar sua declaração no código.</p><h4>Use Nomes Pronunciáveis</h4><p>Novamente, código é escrito para humanos, e não máquinas. Nomes pronunciáveis são importantes inclusive para momentos de debates sobre o código. (ninguém vai gostar de falar &quot;aquele atributo gê ním dê aga eme éssi&quot; para referenciar genymdhms).</p><p>Exemplo de nomes não pronunciáveis:</p><pre>class DtaRcrd102 {<br>  private Date genymdhms;<br>  private Date modymdhms;<br>  private final String pszqint = &quot;102&quot;;<br>  /*...*/<br>};</pre><p>Uma alternativa melhor seria:</p><pre>class Customer {<br>   private Date generationTimestamp;<br>   private Date modificationTimestamp;<br>   private final String recordId = &quot;102&quot;;<br>   /*...*/<br>}</pre><h4>Use Nomes Buscáveis</h4><p>Nomes de uma única letra e constantes numéricas tem um problema particular que eles não são facilmente localizáveis em um texto.</p><p>Por exemplo, na IDE é fácil buscar uma constante <strong><em>MAX_CLASSES_PER_STUDENT</em></strong>, mas encontrar o número 7 pode ser algo complicado. Por isso é bom definir constantes pra estes casos:</p><pre>var MAX_CLASSES_PER_STUDENT = 7;</pre><p>Nomes de uma única letra (o famoso <strong><em>i </em></strong>dentro de um<strong><em> for</em></strong>)<strong><em> </em></strong>devem ser usados <strong>apenas </strong>como variáveis locais dentro de métodos pequenos.</p><blockquote>O tamanho de um nome deve corresponder ao tamanho do seu escopo.</blockquote><h4>Interfaces e Implementações</h4><p>Para as interfaces de Java (ou similares em outras linguagens), há um hábito de prefixar com <strong><em>I</em></strong>. Nestes casos, o autor prefere não prefixar com <strong><em>I</em></strong>, mas adicionar um sufixo <strong><em>Imp</em></strong> na implementação. Por exemplo, ao invés de:</p><pre>interface IShapeFactory { ... }<br>class ShapeFactory: IShapeFactory { ... }</pre><p>Teríamos:</p><pre>interface ShapeFactory { ... }<br>class ShapeFactoryImp: ShapeFactory { ... }</pre><p>Isso de certa forma é coerente, já que muitas vezes é a interface que será pública, enquanto a implementação concreta não será acessada diretamente.</p><h4>Evite Mapas Mentais</h4><p>O leitor não deve precisar traduzir mentalmente os nomes em outros nomes que ele já conhece.</p><p>Por exemplo, um loop pode conter variáveis i,<em> </em><em>j ou </em><em>k.</em>Estes nomes já são tradicionais. Porém, escolher uma variável a<em> </em>seria uma escolha ruim.</p><blockquote>Não há razão pior pra escolher o nome c do que o fato de <strong><em>a</em></strong> e b já estarem sendo usados.</blockquote><p>Uma diferença entre um programador inteligente e um programador profissional é que o profissional entende que <strong>clareza é fundamental</strong>. Profissionais usam seus poderes para uma boa escrita de código que outros entendam.</p><h4>Nome de Classes</h4><p>O nome de uma classe deve ser um substantivo ou uma frase que contenha um. Nunca deve ser um verbo.</p><p>Exemplo de bons nomes:</p><pre>Customer<br>WikiPage<br>Account<br>AddressParser</pre><p>Evite no nome da classe, usar palavras como <strong><em>Manager, Processor, Data, Info</em></strong>.</p><h4>Nome de Métodos</h4><p>Métodos devem ser ou conter um verbo no seu nome. Por exemplo:</p><pre>postPayment()<br>deletePage()<br>save()</pre><p>Métodos que servem pra acessar, modificar ou verificar um predicado devem ser prefixados com <strong><em>get</em></strong>, <strong><em>set</em></strong> e <strong><em>is</em></strong> (padrão javabean):</p><pre>getName();<br>setName(&quot;Victor&quot;);<br>paycheck.isPosted();</pre><h4>Escolha uma Palavra por Conceito</h4><p>Escolha uma palavra por abstração e mantenha ela. Por exemplo, é confuso ter fetch, retrieve e get como métodos equivalentes em classes diferentes. Como você irá lembrar de qual nome é usado em qual classe?</p><p>Outro caso é ter um <em>controller</em> e um <em>manager</em><strong><em> </em></strong>usados para a mesma abstração. Dado que ambos executam a mesma função, é possível dizer a diferença essencial entre DeviceManager e um ProtocolController? Porque não são ambos <em>controller</em> ou <em>manager</em>? Se os nomes são diferentes, esperamos que representem abstrações diferentes.</p><blockquote>Escolha uma palavra por conceito e mantenha essa escolha através do código.</blockquote><h4>Use Nomes do Domínio da Solução</h4><p>Quem lerá seu código será um programador, então não tenha medo de usar termos relacionados à ciência da computação: nomes de algoritmos, nomes de padrões, termos matemáticos, etc. Não é sábio criar um nome diferente para representar um conceito que seus colegas já conhecem por outro nome.</p><p>Por exemplo, o nome AccountVisitor já traz informação para o programador que é familiarizado com o padrão <em>Visitor</em>. Outros exemplos são:</p><pre>UserGraph<br>PlayerQueue<br>CustomerBinaryTree</pre><h4>Use Nomes do Domínio do Problema</h4><p>Quando não há nomes relacionados com ciência da computação, escolha nomes baseados no domínio do problema. Assim, se quem for dar manutenção ao seu código não entendê-lo, ele pode ao menos perguntar para quem entende do domínio do problema.</p><h4>Adicione Contextos Significativos</h4><p>As variáveis firstName, lastName, street, houseNumber, city, state, zipCode juntas claramente formam um endereço.</p><p>Porém, se você ver apenas state , não fica claro sobre o que se trata. Podemos adicionar contexto à esta variável chamando-a de addressState , por exemplo.</p><h4>Não Adicione Contexto Gratuitamente</h4><p>Em Objective-C, era muito comum adicionar prefixos em todas as classes. Por exemplo, se eu desenvolvesse um projeto pessoal, adicionaria o prefixo VM (de Victor Melo) nas classes:</p><pre>VMUser<br>VMAddress<br>VMDataBaseManager<br>...</pre><p>Porém, não precisamos fazer isso na grande maioria dos casos, e isso provavelmente vai dificultar mais na busca por classes na IDE, já que digitar VM<em> </em>irá exibir todas suas classes<em>.</em></p><p>Por fim, algo muito importante é:</p><blockquote>Não tenha medo de renomear algo porque outros desenvolvedores podem reclamar.</blockquote><p>Se você acredita que renomear um elemento irá trazer mais clareza ao projeto, faça isso. Novamente, <strong>código não é escrito para máquinas, mas para pessoas.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad1eb7557e6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Código Limpo: destaques do capítulo 1]]></title>
            <link>https://medium.com/@victorsmelopoa/c%C3%B3digo-limpo-destaques-do-cap%C3%ADtulo-1-ade32203d560?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/ade32203d560</guid>
            <category><![CDATA[código-limpo]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Wed, 20 Nov 2019 22:44:47 GMT</pubDate>
            <atom:updated>2019-12-11T18:54:35.120Z</atom:updated>
            <content:encoded><![CDATA[<p>Nesta história apresento os pontos que mais me chamaram atenção sobre o primeiro capítulo do livro <em>Código Limpo</em>, de Robert C. Martin.</p><p><a href="https://medium.com/@victorsmelopoa/c%C3%B3digo-limpo-destaques-do-cap%C3%ADtulo-2-ad1eb7557e6a">Destaques do capítulo 2</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mUqXpO0Hrnj68OW7RqA3Ng.png" /></figure><p><em>Código Limpo </em>é um livro sobre boa programação. O objetivo é nos tornar mais críticos sobre nosso próprio código, permitindo-nos identificar a diferença de um código bem escrito para um mal escrito.</p><h4>Código Mal Escrito pode Falir uma Empresa</h4><p>Neste primeiro capítulo, vemos um caso de um app que, no final dos anos 80, era muito popular e amplamente usado. Porém, à medida em que o app era atualizado, <em>bugs</em> não eram reparados, aumentou a quantidade de <em>crashes</em>, entre outros problemas.</p><p>Posteriormente o autor descobriu que isso ocorreu pois a empresa lançou o produto apressadamente no Mercado, criando um código extremamente confuso. A cada nova <em>feature</em> o código piorava, até se tornar impossível de receber manutenção. <strong>O código mal escrito literalmente faliu a empresa</strong>.</p><h4>O Grande Redesign no Horizonte</h4><p>A produtividade de um time de desenvolvimento tende a decrescer continuamente à medida que o projeto cresce, até chegar no ponto onde a confusão no código é tão grande que os desenvolvedores demandam uma refatoração do sistema, com um novo design, criado do zero.</p><p>Porém, quando esse novo sistema é terminado (podendo levar até 10 anos), os desenvolvedores que criaram a demanda já saíram da equipe, e os novos desenvolvedores demandam outra refatoração porque este sistema está confuso, e o ciclo continua indefinidamente.</p><h4>Confusão, Gerentes e Requisitos</h4><p>O autor afirma que código se torna confuso não por agenda apertada ou mudança de requisitos, mas porque <strong>nós</strong> <strong>não somos profissionais</strong>. Gerentes e equipes de marketing olham para nós (desenvolvedores) buscando informação para fazerem promessas e se comprometerem; e mesmo quando não fazem isso, nós não devemos ter vergonha de dizer a eles o que pensamos. Nós somos responsáveis pelo planejamento do projeto e suas falhas, principalmente se a falha for causada por código mal escrito.</p><blockquote>Gerentes querem a verdade. Eles podem defender a agenda e os requisitos com paixão, afinal este é o trabalho deles. O seu trabalho é defender o código com a mesma paixão.</blockquote><p>Você não irá cumprir o prazo criando código confuso. Na verdade, a confusão irá atrasá-lo instantaneamente, e forçadamente você irá perder o prazo. A única maneira de cumprir o prazo, a única maneira de ser rápido, é <strong>manter o código sempre tão limpo quanto possível</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*2ZyT35HRo0S5ch-61KMdvA.png" /><figcaption><em>Código limpo </em>é como uma pintura: assim como reconhecemos obras de arte, nós reconhecemos quando um código é limpo e quando é confuso. Porém isso não significa que sabemos como escrevê-lo limpo.</figcaption></figure><h4>Bola de Neve da Confusão</h4><p>Código mal escrito se torna uma bola de neve: a confusão nele tende a crescer com o tempo. Isso se dá pois quem for modificar o código, não irá entendê-lo, e acabará criando mais confusão.</p><h4>Afinal, o que é Código Limpo?</h4><p>Podemos dizer que há diversas escolas de programação, cada uma com uma própria definição sobre código limpo. Neste primeiro capítulo são apresentadas as definições de diversos profissionais, incluindo <em>Bjarne Stroustrup</em> (inventor do C++) e <em>Ward Cunningham</em> (inventor da Wiki). Alguns pontos sobre código limpo destes autores que vale a pena destacar são:</p><ul><li>O código é focado, fazendo uma coisa bem feita.</li><li>O código pode ser lido e melhorado por outros desenvolvedores.</li><li>O código possui diferentes testes.</li><li>O código sempre parece que foi escrito por alguém que se importa com ele.</li><li>Cada nome de função expressa exatamente o que ela faz.</li></ul><p>Por enquanto é isso. Se tiver algo que não comentei e você achar importante, ficarei feliz de saber. Pode responder nos comentários :)</p><p>Abraço!</p><p><a href="https://medium.com/@victorsmelopoa/c%C3%B3digo-limpo-destaques-do-cap%C3%ADtulo-2-ad1eb7557e6a">Destaques do capítulo 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ade32203d560" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Introduction to Algorithms]]></title>
            <link>https://medium.com/@victorsmelopoa/a-quick-introduction-to-algorithms-5b60197f1149?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b60197f1149</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Thu, 20 Dec 2018 01:40:19 GMT</pubDate>
            <atom:updated>2021-08-17T13:40:55.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHBi1ofyorzYxdmP" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplas</a>h</figcaption></figure><p>This is an introduction to algorithms for anyone who is new to this amazing world of computer science 🚀.</p><p>Imagine it is morning, you are at home, watching some TV and eating some donuts. Then, you realize you need to buy beer because later it is going to happen a barbecue at Mark’s house (by the way, imagine you have a friend called Mark). There is a sequence of steps you need to follow, since standing up from sofa until paying for the beer at the closest grocery store. This sequence of steps is called <strong>algorithm</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0kaWe8Pa5ZIdXRu_AhMiQ.jpeg" /><figcaption>Buying beer algorithm</figcaption></figure><p>Computationally speaking, given an input (remembering to buy beer), an algorithm is a computational well defined procedure that will return an output (the beer bought). Well defined means each step is clear and known enough so it can be easily achievable. An algorithm always tries to solve a problem.</p><p>A more realistic example is a sorting algorithm. There are many algorithm to sort a sequence of elements, but let define the BubbleSort, one of the simplest ones (source <a href="https://en.wikipedia.org/wiki/Bubble_sort">Wikipedia</a>):</p><pre><strong>procedure</strong> bubbleSort( A : list <strong>of</strong> sortable items )<br>    n = length(A)<br>    <strong>repeat</strong><br>        swapped = <strong>false</strong><br>        <strong>for</strong> i = 1 <strong>to</strong> n-1 inclusive <strong>do</strong><br>            /* <strong>if</strong> this pair <strong>is</strong> out <strong>of</strong> order */<br>            <strong>if</strong> A[i-1] &gt; A[i] <strong>then</strong><br>                /* swap them <strong>and</strong> remember something changed */<br>                swap( A[i-1], A[i] )<br>                swapped = <strong>true</strong><br>            <strong>end</strong> <strong>if</strong><br>        <strong>end</strong> <strong>for</strong><br>    <strong>until</strong> <strong>not</strong> swapped<br><strong>end</strong> <strong>procedure</strong></pre><p>Now some interesting and brief definitions:</p><ul><li>The input of an algorithm is the <strong>instance</strong> of the problem this algorithms tries to solve (e.g., a list [1, 5, 3, 6] is an instance of the sorting problem).</li><li>An algorithm is called <strong>correct</strong> if for every instance of a problem, it solves the problem.</li></ul><pre>It is interesting to explain better the <strong>corretude</strong> of an algorithm. There are algorithms that, for some instances of a problem, they stop with the wrong answer or they never end. These are not correct algorithms. For some cases, they are still interesting if we can control their error rate.</pre><ul><li>We say an algorithm <strong>solves</strong> a problem if it stops with the correct answer.</li></ul><h3>Problem Examples</h3><p>Now we understood what is an algorithm, some example of problems that are solved by them are:</p><ul><li>Data encryption</li><li>Search engines (like Google)</li><li>Search the better route to a destiny (e.g., Waze)</li><li>Sorting a list of elements (this is a classic. There are many algorithms to solve that).</li></ul><p>There are a lot of other problems solved by algorithms. Now you know what they are, you can start implementing your own. But be careful: do not confuse algorithms with any programming language sintax. An algorithm can be defined even without a programming language. If you want to start implementing algorithms in a language, I would suggest you Javascript or Swift (if you have a Mac).</p><p>Now, it is up to you. You already know what are algorithms, so what problems do you want to solve? You just need to implement the steps, then conquer the world 🌎 🌍 🌏.</p><h3>References:</h3><ul><li><a href="https://en.wikipedia.org/wiki/Algorithm">Algorithm - Wikipedia</a></li><li><a href="https://mitpress.mit.edu/books/introduction-algorithms-third-edition">Introduction to Algorithms, Third Edition</a></li></ul><h3>Above and Beyond</h3><p>The MIT OpenCourseWare is a great source for computer science topics. They made available a class about <em>introduction to algorithms.</em> I recommend you to watch, at least some parts of it (as it is a long video). Their classes are always interesting and well explained.</p><p><a href="https://www.youtube.com/watch?v=JPyuH4qXLZ0">https://www.youtube.com/watch?v=JPyuH4qXLZ0</a></p><p>I hope this story was useful. Thanks for reading! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b60197f1149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Introduction to Elasticsearch with Kibana]]></title>
            <link>https://medium.com/@victorsmelopoa/an-introduction-to-elasticsearch-with-kibana-78071db3704?source=rss-e59cd5367489------2</link>
            <guid isPermaLink="false">https://medium.com/p/78071db3704</guid>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[kibana]]></category>
            <dc:creator><![CDATA[Victor S Melo]]></dc:creator>
            <pubDate>Thu, 18 Jan 2018 21:53:56 GMT</pubDate>
            <atom:updated>2025-04-10T14:39:34.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*AYP0Mg_MwJMm3Kbx8Xa8lQ.png" /></figure><p>This week, I had my first contact with Elasticsearch and Kibana (honestly, my first contact was yesterday). So, I found a lot of tutorials, but most of them go deep in technical stuffs that weren&#39;t really necessary for me right know, making it a bit harder to understand what really matters.</p><p>Then i had an idea: build a simple tutorial focusing on a really basic information about Elasticsearch and <a href="https://www.elastic.co/products/kibana">Kibana</a>, using a simple language to present the starting topics I think everyone should know when starting to learn about it. I gathered the information from different sources and compressed what I thought was most useful here. So, I hope you enjoy this story, and let start learning :)</p><h3>What Is Elasticsearch</h3><p>Elasticsearch is an open source search engine highly scalable. It allows you to keep and analyse a great volume of information practically in real time.</p><p>Elasticsearch works with JSON documents files. Using an internal structure, it can parse your data in almost real time to search for the information you need.</p><p>It is very useful when working with <strong>big data.</strong></p><blockquote>This is an 101 practical introduction to Elasticsearch for people who never had contact with it before.</blockquote><p>Elasticsearch is available <a href="https://www.elastic.co/products/elasticsearch">here</a>.</p><h3>Definitions and other stuffs</h3><p>Some technical (but useful) information to know about Elasticsearch are:</p><ul><li>It is a real time distributed and analytics engine.</li><li>It is open source, developed in Java.</li><li>It uses an structure based in documents instead of tables and schema.</li></ul><p>The great benefits I found about it are speed and scalability. It is implemented in a way to allow querying to be really fast. And about scalability, it can be runned in your laptop or in hundreds of servers with petabytes of data.</p><p>Besides speed and scalability, it has high resiliency relating to failures, and it’s really flexible relating to data type.</p><p>Again, Elasticsearch is very useful for <strong>big data</strong>, making it easy to analyse million of data in almost real time searches. That is the Elasticsearch magic.</p><p>But, how can you search all these datas? For that, you use queries.</p><p><strong>Query:</strong> The language to perform and combine many types of searches like structured, unstructured, geo, metric, etc. You can ask a query “anyway you want”.</p><p>And about analysis, Elasticsearch lets you understand billions of log lines easily. It provides aggregations which help you zoom out to explore trends and patterns in your data.</p><p>For example, if you have a cloud with 500 nodes, you can analyse the entire infrastructure in a short period of time, importing the logs into Elasticsearch and, based on it’s response, you can get to the root cause of an issue in your infrastructure.</p><p><strong>Other examples of use:</strong></p><ul><li>Show data with an specific value. For example: show all 23 years old users from the database.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeHYqNR4AVaQRdIpXSAHXQ.png" /><figcaption>Select data with specific value</figcaption></figure><ul><li>Search data by geography</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVw-l25jBdVmFA55I_TeWA.png" /><figcaption>Search by geography</figcaption></figure><ul><li>Aggregate data by days</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhlLOjauf6AXqtkOQ_7Dgg.png" /><figcaption>Aggregate data by days</figcaption></figure><h4>Clients</h4><p>Elasticsearch is so interesting that it is used by Mozilla, GitHub, Stack Exchange, Netflix, and many more users.</p><h3>Hands On</h3><p>Now that you know a bit about Elasticsearch, let’s go to the practical part of this story.</p><h3>Installation</h3><p>To execute Elasticsearch, you must:</p><ol><li>Install Java: should be version 8 or greater.</li><li>Install Elasticsearch: You can download it from <a href="http://elastic.co/">elastic.co</a> and follow the steps to install in your operational system. If you have MacOS with Homebrew installed, you can install it by simply typing brew install elasticsearch</li></ol><h3>Interface</h3><p>To use Elasticsearch, you will need an interface. In this story I’ll use <a href="https://www.elastic.co/products/kibana">Kibana</a>, a great web interface to visualize and manipulate the data of Elasticsearch.</p><p>It can be downloaded in elastic.co and installed following the steps there presented, or using Homebrew with the following command: brew install kibana</p><p>You need to download the same version for Elasticsearch and Kibana.</p><p>When, in the future, will find yourself needing to develop a software to interact with Elasticsearch, you can use a programming language to interact with it. Some of the programming languages acceptable are:</p><ul><li>Java</li><li>C#</li><li>Python</li><li>JavaScript</li><li>PHP</li><li>Perl</li><li>Ruby</li></ul><h3>Basic Concepts</h3><p>Ok! Now you shall already have Elasticsearch and Kibana installed. Before we start using it, let’s see some useful concepts about Elasticsearch.</p><h4>Elasticsearch is made of</h4><p><strong>Cluster</strong></p><p>A cluster is a collection of one or more nodes that, together, holds the entire data. It provides federated indexing and search capabilities across all nodes and is identified by an unique name (by default it is ‘/ elasticsearch’/)</p><p><strong>Node</strong></p><p>A node is a single server which is a part of cluster, stores data and participates in the cluster’s indexing and search capabilities.</p><p><strong>Index</strong></p><p>An index is a collection of documents with similar characteristics and is identified by a name. This name is used to refer the index while performing indexing, search, update, and delete operations against the documents in it. In a single cluster, you can define as many indexes as you want.</p><p><strong>Document</strong></p><p>A document is a basic unit of information which can be indexed. It is expressed in JSON which is an ubiquitous internet data interchange format.</p><p><strong>Shards</strong></p><p>Elasticsearch provides the ability to subdivide the index into multiple pieces called shards. Each shard is in itself a fully-functional and independent “index” that can be hosted on any node within the cluster. This is useful for the case when an index putted in a single node would take more disk space than available. The index then is subdivided between different nodes. Besides, shards allow you to distribute and parallelise operations across shards, increasing the performance.</p><p><strong>Replicas</strong></p><p>Elasticsearch allows you to make one or more copies of your index’s shards which are called replica shards or replica. It provides high availability in case a node fails, and it allows you to scale out your search volume since searches can be executed on all replicas in parallel.</p><h3>Executing</h3><p>Ok, now, let’s really put our hands on it. Go to the directory where Elasticsearch was installed and execute it through terminal: $ ./elasticsearch.</p><p>If you have installed it using Homebrew, try to type elasticsearch in terminal. It may starts Elasticsearch without needing to go to it&#39;s directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*Z6HyxyQEUfS5hhS7CFsunw.png" /><figcaption>Elasticsearch starting</figcaption></figure><p>Now that Elasticsearch is being executed, open another terminal window and execute Kibana, going to it’s directory and executing $ ./kibana or, with Homebrew, just typing $ kibana in terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*hFhdFO1a7uXPG7_V1VtJ8w.png" /><figcaption>Kibana Started</figcaption></figure><p>If everything goes right, now you shall have both being executed. To verify it, open a web browser and go to: <a href="http://localhost:9200/">http://localhost:9200</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbflLs4sUvzAec8lwzH8kg.png" /><figcaption><a href="http://localhost:9200/">http://localhost:9200</a> result indicating Elasticsearch is running</figcaption></figure><p>If you see a result similar to the above, this means Elasticsearch is up and running.</p><p>To view Kibana interface, go to: <a href="http://localhost:5601/">http://localhost:5601</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_UG0r263s4q69pW9rEftFQ.png" /><figcaption>Kibana interface at http://localhost:5601</figcaption></figure><p>If everything is shown as above, lets play with some data now.</p><h3>Commands</h3><p>In the Kibana interface, select <strong>Dev Tools</strong>, on the left menu. You’ll see a left console to type the commands and a right one to see the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBmcUjurUA_XVJjtc-YW3A.png" /></figure><p>Let’s see the commands available to manipulate data.</p><h3>PUT</h3><p>PUT command allows you to insert a new document data into Elasticsearch. Type the following code in console, press the green play button and see the result.</p><pre>PUT /my_playlist/song/6<br>{<br> &quot;title&quot; : &quot;1000 years&quot;,<br> &quot;artist&quot; : &quot;Christina Perri&quot;,<br> &quot;album&quot; : &quot;Breaking Dawn&quot;,<br> &quot;year&quot; : 2011<br>}</pre><p>The result shall be something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVkN4fuIJMyyeVZKa1PG6Q.png" /></figure><p>This means you just inserted a document data into Elasticsearch. In this example, we have /my_playlist/song/6, where:</p><ul><li>my_playlist: is the name of index you will insert the data.</li><li>song: is the name of the document to be created.</li><li>6: id of element instance. In this case, is the song id.</li></ul><p>If the index <em>my_playlist</em> did not exist already, it will be created, just as the document <em>song </em>and the id <em>6</em>.</p><p>To <strong>UPDATE</strong> a value, you use the same PUT command to the same document. For example, if you want to insert a new parameter, location, you could do it in the following way:</p><pre>PUT /my_playlist/song/6<br>{<br> &quot;title&quot; : &quot;1000 years&quot;,<br> &quot;artist&quot; : &quot;Christina Perri&quot;,<br> &quot;album&quot; : &quot;Breaking Dawn&quot;,<br> &quot;year&quot; : 2011,<br> &quot;location&quot; : &quot;London&quot;<br>}</pre><p>The result shall be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgHlLezom8b7QauemVbOtQ.png" /></figure><h3>GET</h3><p>GET command allows you to retrieve information about your data. Type the following example:</p><pre>GET /my_playlist/song/6</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iq1xWTmmJRF7s2s3WJSCWg.png" /></figure><p>This retrieves the data you have just inserted.</p><h4>DELETE</h4><p>To delete a document, you just need to use the following command:</p><pre>DELETE /my_playlist/song/6</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4NE_RhcIsoMcDbJEbpWdg.png" /></figure><h3>Searching Data</h3><p>Ok, now you know some commands. But, it was presented in a very simple way. Getting a little deeper about this, you can execute more complex queries.</p><p>There are different Search APIs. To keep it simple, I will present just a few and simple examples, but you can find more about it <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search.html">here</a>.</p><p>The parameter used in the examples is <em>q</em>, representing that the query will be executed through URI.</p><p>I will use the accounts JSON file, available <a href="https://download.elastic.co/demos/kibana/gettingstarted/accounts.zip">here</a>.</p><p>To load a data set into Elasticsearch, open the terminal, go to the directory the file downloaded is, then execute the following command: curl -H &#39;Content-Type: application/x-ndjson&#39; -XPOST &#39;localhost:9200/bank/account/_bulk?pretty&#39; --data-binary @accounts.json</p><p>Now you should have the accounts data into Elasticsearch. You can try the following examples:</p><h4>Simple Examples with URI Search</h4><p><strong>Return all accounts from state UT.</strong></p><p>GET /bank/_search?q=state:UT</p><p><strong>Return all accounts from UT or CA.</strong></p><p>GET /bank/_search?q=state:UT OR CA</p><p><strong>Return all accounts from state TN and from female clients.</strong></p><p>GET /bank/_search?q=state:TN AND gender:F</p><p><strong>Return all accounts from people older than 20 years.</strong></p><p>GET /bank/_search?q=age:&gt;20</p><p><strong>Return all accounts from people between 20 and 25 years old.</strong></p><p>GET /bank/_search?q=age:(&gt;=20 AND &lt;=25)</p><h4>Simple examples using Query DSL</h4><p>URI may not be the best way to query Elasticsearch. It seems to be preferable to use QueryDSL instead. Below follows a short description and an example about it, but you can read more about QueryDSL <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.0/query-dsl.html">here</a>.</p><p>Think of the Query DSL as an AST (Abstract Syntax Tree) of queries, consisting of two types of clauses:</p><ul><li><strong>Leaf query clause:</strong> it looks for a particular value in a particular field, such as the <em>match</em>, <em>term </em>or <em>range</em> queries.</li><li><strong>Compound query clause:</strong> it wrap other leaf or compound queries and is used to combine multiple queries in a logical fashion (such as the <em>bool</em> or <em>dis_max</em> query), or to alter their behaviour (such as the <em>constant_score</em> query).</li></ul><p>Query clauses behave differently depending on whether they are used in <em>query context</em> or <em>filter context</em>:</p><ul><li><strong>Query context: </strong>a query clause used in query context answers the question <em>&quot;How well does this document match this query clause?&quot;</em>. The answer is a <em>_score</em> representing how well the document matches, relative to other documents.</li><li><strong>Filter context:</strong> a query clause in filter context answers the question <em>&quot;Does this document match this query clause?&quot;. </em>The answer is a simple YES or NO.</li></ul><p>Below is an example of query clause being used in query and filter context in the <em>search</em> API. This query will match documents where all of the following conditions are met:</p><ul><li>The <strong>address</strong> field contains the word <strong>Street</strong></li><li>The <strong>gender</strong> field contains the exact word <strong>f</strong></li><li>The <strong>age</strong> field contains a number greater or equal to 25</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3R7gxgbRfrTDswn1XWbHw.png" /></figure><pre>GET /_search<br>{<br>  &quot;query&quot;: {                                  //1<br>    &quot;bool&quot;: {                                 //2<br>      &quot;must&quot;: [<br>       { &quot;match&quot;:{&quot;address&quot;:&quot;Street&quot;}}        //3<br>      ],<br>      &quot;filter&quot;: [                             //4<br>        { &quot;term&quot;:{&quot;gender&quot;:&quot;f&quot;}},             //5<br>        { &quot;range&quot;: { &quot;age&quot;: { &quot;gte&quot;: 25 }}}   //6<br>      ]<br>    }<br>  }<br>}</pre><p>Understanding the code:</p><p>//1: The query parameter indicates query context.</p><p>//2 and //3: The bool and match clauses are used in query context, which means that they are used to score how well each document matches.</p><p>//4: The filter parameter indicates filter context.</p><p>//5 and //6: The term and range clauses are used in filter context. They will filter out documents which do not match, but they will not affect the score for matching documents.</p><blockquote><strong>Tip: </strong>Use query clauses in query context for conditions which should affect the score of matching documents (i.e. how well does the document match), and use all other query clauses in filter context.</blockquote><p>Now you know a bit about what is Elasticsearch and how to insert, update, delete and search data on it. Kibana has a lot of more features to view the data, including presenting it as different graphics. I recommend you to explore all of them.</p><p>There are much more about Elasticsearch. What I’ve presented here is just a first step to start understanding it, based on how I understood these topics in my first contact with Elasticsearch. After reading this story, you should explore Kibana interface, the Elasticsearch documentation, how to create more complex queries, and so on.</p><p>I hope this story helped you having your first contact with Elasticsearch, and that now you can read other tutorials and the documentation with less effort.</p><p>Thanks for reading and good luck with your studies :)</p><p><strong>Edit:</strong></p><p>I leave here my thanks to David Pilato, from the Elasticsearch community forum, who helped me indicating some improvements to this tutorial.</p><h3>References</h3><ul><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.1/index.html">Elasticsearch Reference</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search-uri-request.html">URI Search</a></li><li><a href="http://blog.caelum.com.br/buscas-eficientes-com-elasticsearch/">Caelum — Buscas Eficientes com Elasticsearch</a> (it is in portuguese)</li><li><a href="https://www.youtube.com/watch?v=1EnvkPf7t6Y&amp;feature=share">Elasticsearch introduction</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.0/search.html">Search APIs</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.1/docs-bulk.html">Bulk API</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78071db3704" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>