Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Consultation

    Consulting Project Prepare for a new job

    JavaScript

    JAMstack Architecture with Next.js

    Startups

    Crafting an Effective Marketing Strategy for Your Startup

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Sunday, September 28
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / Elastic Search – Basics
    Programming

    Elastic Search – Basics

    Stepan ZharychevBy Stepan ZharychevMarch 11, 2018Updated:April 5, 2019No Comments5 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Elastic Search – Basics
    Elastic Search Basic
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    There’s no secret that in modern Web applications the ability to find required content fast is one of the most important things. If your application isn’t responsive enough, clients will use something else. That’s why all the processes should be optimized as much as possible, which can be a very challenging task…

    … especially with search. What makes the situation even worse is that sometimes the set of search criteria can be simply large. Let’s take a look:

    {
      account_name: 'Test',
      phone: '+420231231220',
      city: 'Prague',
      country: 'Czech Republic',
      email: 'author@gmail.com',
      address: 'Sokolovska, 2',
      secondary_address: 'Radlicka, 107',
      firstname: 'Jindřich',
      lastname: 'Chalupecký'
    }

    Now imagine that you need to search through such entries with pattern match (for PostgreSQL it can be done via LIKE command) while you might have thousands of such entities. The query will be very complex and heavy in that case, and you might need to join some data after all:

    SELECT *
    FROM   customers
    WHERE  account_name LIKE 'query%' OR 
           city LIKE 'query%' OR
           country LIKE 'query%' OR
           email LIKE 'query%' OR
           firstname LIKE 'query%' OR
           lastname LIKE 'query%'
    

    Resolving such tasks is not a new kind of problem. Years ago the search indexing process was invented. The main idea is to store only searchable parts of the document and optimize the process of going through such parts. If we want to search through large entries and we know exactly what parts we’re going to search for, we can just add them into the index to do substring search faster using a search engine. (There’re many other optimizations in a search engine. You can read about the specifics here.)

    One of the most popular search engines is Elastic Search, which we’re going to use with PostrgreSQL and Node.js to build a searchable grid with the entry schema above. But let’s discuss the communication between the components first:

    Workflow of Elastic Search integrated environment (Node + PostrgreSQL)

    The process goes in the following way:

    1. Client requests data from the server API;
    2. Instead of taking data immediately from the DB, server requests ids from ES index;
    3. Elastic Search Engine goes through the indexed entries (and indexed parameters) inside and selects only ones that meet the search criteria;
    4. PostgreSQL selects entries based on the ES result identifiers array;
    Read More:  Think Like a Pythonista -- Building a Book Sharing App

    In our case (you can test the code base yourself, the link is below) we’re going to search through 10000 entities. For the search index we’re going to take just a few parameters with one customized  (but again you can change the algorithm of entities’ generation and test performance, the request will be really fast). In that case the configuration for our ORM model can look like this (in order to make code simpler we used Sequelize ORM, nothing outstanding, just common ORM) for search usage later:

    model.getSearchOptions = () => {
        return {
            type: 'customers',
            keys: ['account_name', 'city', 'country' ]
        }
    }

    Here we specify what name of search index collection is going to be used and what properties of actual data should be indexed. There’s one rule for you guys: know your data and queries! Never index everything that’s saved in DB if it can be avoided. Analyze for what kind of data the user expects to have a search. For example, if we had a phone number book, I would index phone, last name and first name as most common searchable fields. But how are those props connected with actual search index? Good question. And here we need to discuss another pitfall of ES usage – data duplication:

    Shows the way how entry is properly saved inside Search Index

    So each change in the database should be reflected in the search index. We save the same data twice. Sounds a bit complex, but there’s the easy way: usage of middleware!

    Shows the middleware layers between API and actual DB

    Actually we already have one – Sequelize ORM. Nowadays it’s common practice to use ORM as a provider of connection to DB to have all the models, relations, etc. easily readable and well-structured. We can use ORM functionality for the same purpose: it will provide the interface for indexing inside ES server. So we’re going to kill 2 birds with one stone – change index and db with one abstraction with no duplicate code every time when we need to do such operations (the idea is not a new one, you can easily find such extensions for another ORMs, like mongoosastic for MongoDB ORM). But if there’s no ready-to-use solution, you might need to decorate the existing create/update/delete methods. Let’s take a look at a possible way:

    module.exports = (model, client, database) => {
        const originalCreateMethod = model[methods.create];
        const options = model.getSearchOptions();
    
        model.originalCreate = originalCreateMethod;
    
        model[methods.create] = async entry => {
            return new Promise(resolve => {
                model.originalCreate(entry).then(created => {
                    let body = {};
    
                    options.keys.map(key => {
                        body[key] = created[key];
                    });
    
                    client.index({
                        index: `${database}_${options.type}`,
                        id: created.id,
                        type: 'doc',
                        body
                    }).then(() => resolve(created));
                });
            });
        };
    };

    As you can see, we provide decorator in the form of a module. It saves the original create method and extends with Elastic Search indexing functionality. So whenever the user calls original ORM create, it will automatically create the search index of the created entity. You can easily do the same extension for update and delete as well.

    Read More:  Create simple POS with React, Node and MongoDB #3: setup E-mail pipeline with add activate on SignUp

    And now when we have our data indexed, it’s a time to do a simple search. We’re going to do the promised substring search:

    esClient.search({
      size: 1000,
      index: `${config.dbName}_customers`,
      q: `*${queryVal}*`
            })).hits
               .hits
               .map(entry => entry._id);

    So we do a search for query pushed by the user and filter out identifiers in the form of array so it can be used for querying of entries from the actual DB.

    Waiting for your comments and questions below! All the code can be found here.

    We are looking forward to meeting you on our website blog.soshace.com

    node
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Stepan Zharychev
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    JavaScript August 12, 2016

    Agile Software Development, Scrum part 2

    In the previous article we talked about an Agile development history, its famous manifest and some Scrum appearance history. Today we will talk about Scrum itself, how it looks like from the inside, how it works also. As it had shown in a previous part of our article, Agile development is a bit more focused on a market needs and stakeholders’ interests comparing with some technologies like waterfall, for example (it does not mean that this technology is bad anyway).

    23. Node.js Lessons. Domains, asynchronous try.. catch. Part 2.

    November 17, 2016

    Уроки React. Урок 11. Pt.2.

    October 31, 2016

    Effective Strategies to Overcome International Recruitment Challenges

    December 6, 2024

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Enhancing Software Development Efficiency with Agile Methodology

    Development November 24, 2024

    React and AJAX – The Art of Fetching Data in React

    JavaScript January 6, 2020

    Essential Recruitment Metrics: Key Measures for Success

    Recruitment November 25, 2024

    Navigating Remote Project Management Challenges: Best Practices

    JavaScript November 30, 2024

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Franchising

    A Guide to HR Developing Performance Goals

    Flask

    Integrate LDAP Authentication with Flask

    Programming

    Уроки React. Урок 11. Pt.1.

    Most Popular

    Using Feature Flags for A/B Testing & Optionally Enable/Disable Features in Your NodeJS Project

    JavaScript

    Strategies for Enhancing Customer Retention in Startups

    Startups

    Forget About Auth0: Implementing Authentication with Clerk.dev in Your Next.js App

    JavaScript
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.