<?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 Gabriel Valensuela on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Valensuela on Medium]]></description>
        <link>https://medium.com/@gabrielValensuela?source=rss-4f6aabb5493c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SEj_1Drid8bgRVQy</url>
            <title>Stories by Gabriel Valensuela on Medium</title>
            <link>https://medium.com/@gabrielValensuela?source=rss-4f6aabb5493c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:48:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabrielValensuela/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[Pagination with ElasticSearch using NodeJS]]></title>
            <link>https://levelup.gitconnected.com/pagination-with-elasticsearch-using-node-js-3fd6c5d2adb1?source=rss-4f6aabb5493c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd6c5d2adb1</guid>
            <category><![CDATA[elasticsearch-performance]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Gabriel Valensuela]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 19:49:00 GMT</pubDate>
            <atom:updated>2020-06-10T14:08:21.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*563tBjMv1FD12DfxRYyOWA.png" /></figure><p>Hey guys, today I’m going talk about what was my strategy on backend to paginate using Elasticsearch.</p><p><em>Reason:</em></p><p>I was assigned a task to develop a page that would contain more than 500 products on it and on these pages, there would be a lot of product data in addition to many product images, and even a product could contain more than one image.</p><p>In this application, we were using Elasticsearch, so initially I wanted to check what it would be like to have a page loading all products without pagination.</p><p>To exemplify, an item would be sort like this object:</p><pre>{</pre><pre>  &quot;id&quot;: 123,</pre><pre>&quot;image&quot;: [&quot;http://...&quot;,http://...,http://...],</pre><pre>  &quot;base_produto&quot;: &quot;&quot;,</pre><pre>  &quot;categoria&quot;: &quot;&quot;,</pre><pre>  &quot;cor_produto&quot;: &quot;&quot;,</pre><pre>  &quot;data_primeira_venda&quot;: &quot;2100-12-31&quot;,</pre><pre>  &quot;desc_cor_produto&quot;: &quot;&quot;,</pre><pre>  &quot;desc_produto&quot;: &quot;&quot;,</pre><pre>  &quot;distribuicao&quot;: false,</pre><pre>  &quot;programacoes&quot;: [</pre><pre>    {</pre><pre>      &quot;nome_programacao&quot;: &quot;&quot;,</pre><pre>      &quot;qtde_entregue&quot;: 0,</pre><pre>      &quot;qtde_programada&quot;: 220</pre><pre>    }</pre><pre>  ]</pre><pre><em> ...</em></pre><pre>}</pre><p>So I tested the page loading all 500 products at once, this was the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FchbcGgP5VzQwEYtJ4D%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FchbcGgP5VzQwEYtJ4D%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="250" frameborder="0" scrolling="no"><a href="https://medium.com/media/09a0b72ef4cb1c0df073a817e3322ba0/href">https://medium.com/media/09a0b72ef4cb1c0df073a817e3322ba0/href</a></iframe><pre>As can be seen, the page is not performing at all and loading takes extremely long, that&#39;s because it&#39;s very high load to the browser to render 500 hundred items and a lot of Images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqPOwjFa2-ys3BKjXBapjA.png" /><figcaption>Network tab showing the number of itens</figcaption></figure><p>Ok, so we see that we REALLY need to paginate that data.</p><p>Now I’m going to present my strategy so that we can page the data by looking only at the backend side.</p><p><strong>Here we use NodeJS and express to handle the routes.</strong></p><p>The elastic search already has a way to deal with pagination and it&#39;s called <strong>SCROLL</strong></p><p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.7/search-request-body.html#request-body-search-scroll">Request Body Search | Elasticsearch Reference [7.7] | Elastic</a></p><p>the scroll basically has 2 main parameters:<br><strong>scroll</strong>: <em>scroll parameter tells Elasticsearch to keep the search context open for the period of time you are spending.</em></p><p><strong>scroll_id</strong>: <em>It is the reference that will be used to search for the next page of items.</em></p><p><em>example of a scroll POST:</em></p><pre>POST /_search/scroll <br>{<br>    &quot;scroll&quot; : &quot;1m&quot;, <br>    &quot;scroll_id&quot; : &quot;DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAD4WYm9laVYtZndUQlNsdDcwakFMNjU1QQ==&quot; <br>}</pre><p>So, basically on the backend we create a function that searches our items and receives two parameters: <strong>indexName</strong> and <strong>query</strong>.</p><p><strong>indexName</strong>: <em>name of the index where Elasticsearch will search.</em><br><strong>query</strong>: <em>the query we are using to filter the items and etc…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*jreuajJMlOyCugIkHJfCig.png" /><figcaption>searchData</figcaption></figure><p>What is this <strong>searchData</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NH2EcDB4oNPtzg-kGeEttw.png" /></figure><p>basically it is the endpoint of our elastic application.</p><p>( <em>To better dive into this I recommend the proper documentation of the elastic</em>: <a href="https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html">https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html</a> )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*YnA9iH9751o6ElBTAP5b3Q.png" /><figcaption>Route <strong>getSingleCollectionProducts</strong></figcaption></figure><p>Now I’m going to show you a route that takes the first 10 items from the 500 hundred products that I had.</p><pre><strong>async</strong> <strong>getSingleCollectionProducts</strong>(req, res) {</pre><pre><em> const</em> <em>{</em> <em>collection,</em> <em>id_marca_estilo,</em> <em>next_page </em>} = await req.query;</pre><pre> const payload = {<br> <strong> //<em>HERE</em> <em>I`M JUST PUTTING TO ONLY RETURNS TO ME<br>  // 10 ITEMS</em></strong><em><br>  from</em>: 0, <em>size</em>: 10,<br> },</pre><pre> query: {<br> <strong> //here will enter your query, you can use your on query<br>  // on kibana.</strong><br> },</pre><pre>};</pre><pre>try {                         <strong>//<em>indexName</em></strong>    <strong>//<em>Query</em></strong><br><em>const</em> <em>resp</em> <em>=</em> <em>await</em> <em>searchData(&#39;produto_cor&#39;,</em> <em>payload);</em>  <br> <strong>//<em>RETURNS</em> <em>TO</em> <em>ME</em> <em>AN</em> <em>ARRAY</em> <em>OF</em> <em>DATA</em> <em>FROM</em> <em>0</em> <em>TO</em> <em>10</em></strong></pre><pre><em> const</em> <em>produtos</em> <em>=</em> <em>[]; </em><strong><em>// just creating an more useful array of datas</em></strong><em><br> await</em> <em>resp.body.hits.hits.map(products</em> <em>=&gt;</em> <em>{<br>  produtos.push({<br>   id</em>: <em>products._id</em>,<br>   <em>data</em>: <em>products._source</em>,<br> });<br>});</pre><pre> const <strong>pro</strong> = {};<br> // because i used the parameter <strong>scroll</strong> on my <strong>searchData function</strong>,<br> // I have the <strong>scroll_id</strong> value</pre><pre> pro.next_page = resp.body._scroll_id; <br> <strong>// I create a value on my object that has the value from the next <br> // page</strong><br> <br> pro.data = produtos;</pre><pre> return res.status(200).send(<strong>pro</strong>); // return the value </pre><pre>} catch (err) {<br><em>  console.log(&#39;Error</em> <em>getting</em> <em>products</em> <em>from</em> <em>a</em> <em>single</em> <em>collection&#39;,</em>     <em>err);</em></pre><pre><em>  return</em> <em>res.status(500).send(err);<br>  </em>}<br>}</pre><p>When we hit this route The final result will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCDEu6eD_epaUgXlKabikA.png" /><figcaption>10 items and now we have the scroll_id</figcaption></figure><p><strong>Pay attention, our <em>scroll_id</em> is now called <em>next_page.</em></strong></p><p>Now the page is extremely faster because we are only loading the first 10 items.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZ9DMDSrvLaC1dpxJS5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZ9DMDSrvLaC1dpxJS5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="250" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b51a704753058f3bf7d6e9c4eff017d/href">https://medium.com/media/5b51a704753058f3bf7d6e9c4eff017d/href</a></iframe><p>Our goal now is to load the next items.We have now the <strong>scroll_id </strong>that<strong> </strong>I<strong> </strong>called next_page who has the id for the next page of items that we want to render.</p><p>Now it’s the simplest part, we just need to create one more route that contains the <strong>scroll_id</strong> as a parameter, and Elasticsearch will take care of returning us the next data and also a new scroll_id containing the next items on the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*QL-qiIsgNcobjdK5FZpyVw.png" /><figcaption>The route for the next page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-owQ3XHXWltlRsbcUNhhuQ.png" /><figcaption>the next page of items</figcaption></figure><p>Virtually the same as a route that was previously created, with only the detail that now instead of using searchData, we had to create a new function called scrollData that came with the elasticClient(<a href="https://github.com/elastic/elasticsearch-js">https://github.com/elastic/elasticsearch-js</a>)</p><p>( <a href="https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/scroll_examples.html">https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/scroll_examples.html</a> )</p><p>Basically the scroll function receives two parameters:</p><pre>scroll_id: String(id of the next page containing the next 10 items)<br>scroll: String(number of times that the id will exist)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*k-mLeemtoySaKwa3o8UKmQ.png" /><figcaption>scrollData function</figcaption></figure><p>After changing some things on the front end, to use my created routes we have our result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSRrGMNfLhfy3iCRct7%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSRrGMNfLhfy3iCRct7%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="250" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c190b033e9ae83fe0650ea68b41bc98/href">https://medium.com/media/4c190b033e9ae83fe0650ea68b41bc98/href</a></iframe><p>ElasticSearch is an amazing tool with its own world, many doubts may appear along the way, but if you need help you can look for me, I hope I helped!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd6c5d2adb1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/pagination-with-elasticsearch-using-node-js-3fd6c5d2adb1">Pagination with ElasticSearch using NodeJS</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>