Categories
Blockchain Financial Services Software

Hyperledger fabric – what do you need to know about this enterprise blockchain?

Enterprises need to ensure a significant level of security, privacy, compliance, and performance. These processes are very complex and time-consuming. Problems frequently emerge with data incompatibility or lack of trust. How can Hyperledger Fabric help in such situations?

Blockchain is a distributed, decentralized public ledger. To picture it, it can be described as a constantly growing list of transactions stored on devices on the network called nodes. Cryptographic protocols connect the nodes and keep transactions confidential.

All the data on the blockchain network is visible to users, and each is responsible for their actions. Data is immutable and not controlled by one central authority. But what happens when we want to use blockchain for business so that we need to certify authorities and control who is in our network, and we want to keep all our data confidential from the outside world? One thing is for sure – in such a case, a public blockchain network won’t be suitable; you need a private network. To create blockchain applications meeting the above requirements, it’s best to use enterprise blockchain platforms.

What are private blockchain networks, and what are their benefits

Private blockchains are a version of blockchain technology that can be either open-source, consortium, or privately developed. There is a wide range of private blockchain platforms, but the most popular ones are Hyperledger Fabric (sometimes shortened to Fabric, or HLF) hosted by the Linux Foundation, and R3’s Corda.

Joining a private blockchain network

One feature that sets private blockchains apart is that participants can limit or grant permission to access this blockchain network. This is why it is also called a permissioned network. Network administrators have to invite you to join the enterprise blockchain. Limiting access to the network and implementing proper identity management ensure private transactions. Only entities participating in a transaction will know about it. “To achieve a higher level of privacy, it is sufficient to specify user identities, limit read permissions, and certify authorities. These measures provide a high level of data protection.

Transaction scalability across the network

Hyperledger Fabric is an open-source blockchain; its scalability depends on many factors. Software infrastructure design and complexity impact performance. The Hyperledger Foundation claims that its private blockchain is more scalable and allows more transactions per second than public blockchains. A 2019 study by Christian Gorenflo, Stephen Lee, Lukasz Golab, and S. Keshav even states that it has achieved a fantastic transaction flow of up to 20,000 business transactions per second.

One significant tradeoff for higher transaction processing rates is that private blockchains are more centralized, permissioned networks. Rather than public proof-of-work consensus, which Bitcoin and Ethereum use, Hyperledger Fabric networks use the Raft consensus algorithm.

Consensus in Hyperledger Fabric network

To reach consensus in HLF, you need an odd number of nodes, and there needs to be a simple majority of those working to confirm transactions. For example, if there are seven nodes in a network, four would need to be working to verify new transactions. However, having such a limited number of nodes also comes with risk.

Blockchain developer Tomasz Kaliszuk explained that “Raft [consensus] might lose more nodes, and it will continue to work. It is an approach to a consensus that enables actors in a network to gain a lot of power — so be sure it’s someone you trust. It is less secure because it does not protect against ‘bad actors,’ meaning ‘bad nodes,’ so it’s essential in enterprise blockchains to trust that such bad users will not gain access. Raft, however, is faster, much more scalable when it comes to network expansion.”

When designing blockchain systems based on Hyperledger Fabric, we approach it from a technical point of view using its built-in components like chaincode and ordered. But we also approach it from the perspective of business logic. We try to understand how our client’s business works, what problems we are to solve, and how we can combine technology and business to optimize processes and bring tangible benefits.

What is Hyperledger Fabric blockchain platform– need-to-know basis

Hyperledger Fabric supports transaction validation. This blockchain network is characterized by a modular architecture that breaks down transaction processing into phases. This separation is intended to optimize network scalability and performance.

Permissioned blockchain ledger and smart contract model

Distributed ledger technology includes blockchain technologies and smart contracts called chaincode. Moreover, we can build a traditional application using, for example, node.js technology and use blockchain as a layer for synchronizing, processing, and securing data. That can work well in the context of financial sectors, for example.

Secure transactions based on blockchain infrastructure

Using Hyperledger Fabric allows a high level of security. The blockchain framework raises several concerns related to competitiveness, protection laws, rules regarding confidentiality of personal data, the risk of data leaks, and the management of private data. All of them can be mitigated thanks to partitioning the data in the network that is also available in Fabric.

Use case of Hyperledger Fabric blockchain technology for business

I want to present the case of our recent Hyperledger project. On the high-level architecture above, you can see the structure of the decision-making business processes before the implemented changes. Making and confirming a decision or approving a document requires that all parties communicate with each other to agree to the changes at the same time.

Communication between the systems of partners or branches in one organization was processed without a central trusted data source that would guarantee that the transaction details confirmation of all members of this network would be fast and saved information in the database would be the same. This structure’s convoluted and time-consuming.

Central database solution pros and cons

As shown in the diagram above, we can add a back-end system with a database as a central solution. This solution could improve the process between participants in business networks like this one. However, we still have a problem with distrust and a lack of immutable data. The data transferred between participants can be changed without the consent of the settling parties, resulting in a potential asymmetric version of data in at least one of the system participants. The lack of trusted data affects future transactions and will not resolve our problems. The optimized, centralized database could be faster and easier to search in than decentralized solutions.

Distributed network pros and cons

Data immutability and trustless data exchange were essential; we decided to use DLT as a private blockchain infrastructure with intelligent contracts to resolve these problems. The blockchain will become a root of trust that makes communication between peers symmetrical and eliminates levels of trust fluctuations or its complete lack.

Solution

A private blockchain is the most relevant solution in this use case. We solved this problem with smart contracts and created a blockchain network – Hyperledger Fabric decentralized ledger technology is one data source in which all saved changes are visible to users. Each participant in the blockchain network can be transparent with others.

By implementing the private blockchain as distributed ledger framework, the client gained one common root of trust – a database with consistent data, which solved the problem of lack of trust. By optimizing current manual or semi-automation processes, decision-making time has been shortened, which also reduced the costs of the process and decision delays.

We are helping various businesses with powerful enterprise blockchain solutions based on Hyperledger Fabric. Contact us, and one of our experts will get in touch with you.

Related posts:

Categories
Blockchain Software Technology

Multi-cloud deployment of blockchain infrastructure

Cloud (or Cloud Computing) was one of the largest buzzwords of the last decade. Still many people identify “the cloud” with Amazon Web Services. Despite that, there are several other cloud computing vendors that are worth looking at, especially if you’re building a blockchain solution supporting a large group.

These are primarily cloud service providers Google Cloud Platform, Microsoft Azure, Oracle Cloud, IBM Cloud, Rackspace and Hetzner Cloud. Below, I’ll discuss their advantages and show how we deployed our blockchain infrastructure.

Multi-cloud deployment of blockchain infrastructure

Table of contents:

  1. The domination of AWS
  2. Location, location, location
  3. More pros and cons of other cloud computing vendors
  4. Espeo’s solutions
  5. Let’s take a look at our entire blockchain infrastructure:
  6. Conclusion

The domination of AWS

Amazon’s domination among cloud providers in the minds of people is somewhat justified because Amazon was the precursor and main promoter of the concept of cloud computing. Amazon’s services are the most known, have the highest reliability, the best documentation. In short, they’re the role model for the competition.

But there are also a number of other vendors that provide private clouds and public clouds. Some examples are the Chinese Alibaba Cloud or the Polish e24cloud. These are more or less successful AWS clones and have even more or less similar APIs. Most often, technologically they don’t bring anything new, but they operate in regions poorly handled by competitors (e.g. Alibaba Cloud in China).

Location, location, location

Let’s begin with data center locations. As I’ll show later, this might be an issue for blockchain infrastructure. With the increase in the physical distance between the client and the data center, network delays increase. In transaction systems, this may determine the order of transaction processing from individual clients, and consequently, profitability or other economic parameters.

AWS covers most of the world but doesn’t have data centers in Africa, China, and Russia. The data centers in India, Brazil, and Australia don’t offer a full range of services. So if we want to start a service strongly dependent on the quality of connections (e.g. blockchain network or high-frequency trading), then it may be reasonable to take multicloud approach and use several different cloud vendors at the same time.

Multicloud strategy translates into various advantages, for instance one of the main pros of Microsoft Azure is having over 50 data centers in various regions of the world. These include the central states of the USA, Eastern Canada, Switzerland, Norway, China, India, Australia, South Korea, South Africa or the United Arab Emirates — in these regions AWS offers relatively large network delays.

More pros and cons of other cloud computing vendors

Google Cloud Platform

In addition to services based on open-source software (Linux, Docker, MySQL, Postgres, MongoDB, HBase, etc.), also provides its own services. These are, for example, BigTable and Realtime Database. They allow more efficient operation of large amounts of data than if you’re using only open source technology, as well as more efficient load balancing than AWS services. The price for this, however, is vendor lock-in, i.e. the impossibility of departing from this particular vendor.

Microsoft Azure

In addition to a number of locations, is also the best place to run all kinds of solutions based on Windows. This can be important if in our blockchain stack we use ready-made .NET libraries that don’t have their own implementations for Linux.

Hetzner Cloud

It’s a relatively new service of Hetzner Online, so far specializing in web hosting and low-cost dedicated servers. The Cloud offer brought a significant improvement in quality in relation to the current offer while maintaining very low prices. It still can’t compete with AWS in terms of stability, but it seems to be a matter of time. Its unique advantage is a data center in Finland.

Espeo’s solutions

Let’s take a look at the solutions we’ve used in Espeo for multi-cloud infrastructure management as well as the blockchain platform itself for blockchain infrastructure.

First approach — manual management

Our blockchain journey with working on distributed ledger technologies on cloud was, of course, manual management. By this, I mean logging into different cloud consoles from several different browsers. This approach worked quite well until we were in control of about 5-6 AWS accounts and one account for each other cloud vendors. With so few accounts, it was still possible to manage them so efficiently “on foot.” It seemed that the investments in the implementation of appropriate tools would take way too long to start paying off, especially that we didn’t know what technologies to stick to and which ones to avoid.

Second approach — tools. Open source?

The second approach was to analyze the available tools, but we wanted them to be open source tools. We were interested, among others, in the Terraform tool (from the creators of Vagrant). Very quickly, however, we got the impression that almost all existing open-source tools didn’t line up with how we work. So, either to manage your own infrastructure (for one company or one group of companies) or in the best case for managing large projects in the Infrastructure as Code model. The latter means describing the infrastructure elements in the form of a language specially created for this purpose.

Infrastructure as Code is, of course, a very sensible approach, but it has a disadvantage. It doesn’t work well for very small projects, which are often at the MVP stage and operate on a single server. In such cases, the Infrastructure as Code approach is to shoot a fly with a cannon. You’ll achieve it, but clients will want to know why they’re paying so much for it.

Third approach — Polynimbus

Ultimately, we decided to use the Polynimbus tool. It supports multicloud environments – eight different cloud vendors and have a competitive advantage of being a relatively simple (compared to Terraform) cloud resources pool, which perfectly suited our needs. Polynimbus supports an unlimited number of AWS accounts and requires minimum configuration for each of them. It basically covers only issuing the access key, secret access key, and the default region. All the rest, including e.g. fast changing AMI ID numbers of system images, are detected automatically.

Let’s take a look at our entire blockchain infrastructure:

As you can see, Polynimbus is one of the elements of a perfectly integrated stack. It covers the management of the full lifecycle of the instance, regardless of whether they are instances of AWS (EC2), Azure, Oracle or others. Creating an instance looks like this:

  • Polynimbus – proper creation of a new instance.
  • ZoneManager – adding a DNS record to Amazon Route53, binding the destination hostname to the IP address returned by Polynimbus.
  • Server Farmer – provisioning of the instance; at this stage various aspects of server security are configured. Central logging of events, backups, automatic updates, and then the instance is plugged into the farm (ie the central management system).
  • Ansible – application provisioning, starting with Docker and support tools. Then the Go stack is built (non-standard due to Hyperledger requirements), after which Hyperledger Fabric and Consul services are installed and configured. The latter in client or server mode. In general, there is no real need to run more than two Consul instances per single availability zone.
  • Next, the integration with a separate Apache Kafka cluster is configured, as well as with CircleCI.com responsible for the CI / CD processes, ie deployment of new versions of the application. So, the next step would be to start the Fabric node by CircleCI.com.

Conclusion

What’s important for both us and our clients, Polynimbus gives us full independence from any cloud vendor. Therefore, if we get a dedicated, more advantageous price offer, e.g. from Oracle, we don’t have to stay with AWS to provide blockchain services to our clients just because of some technical reasons.

One must remember real limitations. Not all power of each subsequent instance can be allocated to the proper application because one must remember about Consul cluster — so that Hyperledger connects to Consul in its own availability zone. And therefore, each of them must contain one or two Consul instances.

Thanks to this, we avoid a situation where global network failure causes problems with the correct operation of the application. In a correctly configured multi-cloud environment, multi-region, multi-AZ… In the case of global network failure, selected nodes simply cease to support current traffic. However, this failure doesn’t result in any other consequences. Thanks to an efficient management stack, in this case, if we anticipate longer problems, we’re able to add new blockchain nodes in other cloud vendors and regions.

Categories
Design Software Technology

Microinteractions: The Power of Animations in Android Apps

Good design is simple and informative, but apps can also be beautiful and sophisticated. Steve Jobs said details mattered and one opportunity to capture a user’s attention is to communicate with them via the details. Here is where microinteractions comes into play.

Microinteractions are the small details that make interacting with an electronic device more natural and pleasant. One example of such microinteractions are animations and we will focus on them here.

Microinteractions: Animations in Android Apps

We will show you how to improve your app with easy but useful animations in Android apps. Before showing examples, we will discuss what you can gain by adding microinteractions to your app.

Animations improve communication and make it easier to understand what is happening on the device. They make an app more pleasurable to use and give the impression of a well-built app.  This in turn will make your users use your app more often, and be more active and involved with it. Consequently, they will use your app for longer, increasing your retention rate as well making it more likely they will recommend it to their friends and increasing your user numbers.

These are advantages of microinteractions so it’s time to see some examples!

Like Animation

Many apps have likable content. To make “giving likes” more interesting and friendly you can add animation like the one used by Instagram. This is the simplest way to start with microinteractions. See below:

Microinteractions: The Power of Animations in Android Apps

Removing & Inserting Items on a List

Sometimes we want to remove or insert items on a list. The worst thing is having to refresh the entire list even after only one change. It’s much better to animate only the items which have changed. See below:

Microinteractions: The Power of Animations in Android Apps

Transition Animation Framework

A lot of apps have lists containing images as well. To make browsing more pleasant, a very good option is to follow Material Design guidelines and use animation in transition between views.

Microinteractions: The Power of  Animations in Android Apps

Smooth App Bar Layout

If your app has scrollable content with an image at its start, you can use another Material Design solution, which is an app bar with a parallax effect. It can be very useful for things such as a user’s profile.

Microinteractions: The Power of Animations in Android Apps

Loading Button

Many apps use buttons to download content and experience shows that users like to know that something is happening once they have pressed a button. There are various ways this can be done but one of the most effective is the one we use which is to create an animation to show the user the current state of the app.

Microinteractions: The Power of Animations in Android Apps

Summary

Microinteractions are a very important part of building apps. Users expect apps which to resolve problems, provide value or give some kind of entertainment. Users appreciate well-built apps with clear and enjoyable designs. They also often express the pleasure they derive from graphics and animations, and which rarely occur in a mobile app.

The examples shown above are quick and simple to implement and are extremely worthwhile doing. As mentioned above apps with animations have a big advantage over others and provide an easy and proven method of getting users involved with your service and improving your app rates and stats.

Interested in more tips for Android apps? Check out our article Android App Development – Trends for 2018 

You have a mobile idea. We have the needed experience to get you there. Check out our services: Mobile App Development

[contact-form-7 id=”13387″ title=”Contact download_8_reasons”]
Categories
Software Technology

How to personalize search results with Elasticsearch

Only a few years ago, a simple search engine was enough — that is a search criteria based on a relational database was enough. Yet, there are no universal and irreplaceable solutions. Thanks to data growth, new search tools have appeared. An undeniable advantage is their ability to influence search results and sorting. I’d like to provide a few examples of how to personalize search results with Elasticsearch.

Searching for data is and will be an indispensable part of almost every web application. In the past few years, the approach to data searches has changed. With the development of web applications and the moving of large sets of data to online services, the amount of data has increased rapidly. Existing search tools and solutions have become insufficient. A good, old search engine based on MySQL is no longer fast and flexible enough.

How to personalize search results in Elasticsearch

Table of contents:

  1. What can those new search tools do?
  2. Code introduction
  3. Example 1: Personalize search weights
  4. Example 2: Personalize results with score functions
  5. Example 3: Score script
  6. Conclusion
 

What can those new search tools do?

A search engine used for searching through job applications would be a great example here. Let’s say that we have a web application with multiple companies. Each company stores user job applications. Almost everyone knows how hard it is to get a good employee that fits our requirements.
Our search engine needs to have multiple search criteria. This sounds quite easy, but what if every company wants to search for applicants in its own, personalized manner? There are many ways to do this. One of them is to add “weights” to certain search parameters. Going further, we can attach these weights to a certain company and give their company admins permissions to manage them.
Elasticsearch is one of the search tools that help you create a search engine with personalized weights. We can now create an advanced search engine in an easy way. What’s more, we’ll have the possibility to affect the results. Thanks to Elasticsearch, we not only get an advanced search engine. We ensure the scalability and easier development of our application in case new functionalities are added in the future.
The examples here are based on the current version — Elasticsearch 6.8.11 and is an update to a previous guide.
I’d like to base on two types of variables attached to user applications:
Let’s say we’ve got two statuses of employment types:
1 – Permanent job
2 – Temporary job
and two statuses of work types:
1 – Full time
2 – Part time
I filled Elasticsearch with some sample data:
RECORD ONE (candidate1):
Employment type = 1
– Work type = 1
RECORD TWO (candidate2):
Employment type = 2
– Work type = 1
RECORD THREE (candidate3):
Employment type = 1
– Work type = 2 

 

Code introduction

A basic search query and its result without weights looks just like this:
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

GET gs_application/application/_search
{
  "_source": [
    "fullname"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "profile.work_types",
            "query": {
              "bool": {
                "must": [
                  {
                    "terms": {
                      "profile.work_types.id": [
                        1
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "profile.employment_types",
            "query": {
              "bool": {
                "must": [
                  {
                    "terms": {
                      "profile.employment_types.id": [
                        1
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

[/dm_code_snippet]
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

{
  "took" : 5,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 2.0,
    "hits" : [
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "78",
        "_score" : 2.0,
        "_source" : {
          "fullname" : "surname1 candidate1"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "79",
        "_score" : 1.0,
        "_source" : {
          "fullname" : "surname2 candidate2"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "80",
        "_score" : 1.0,
        "_source" : {
          "fullname" : "surname3 candidate3"
        }
      }
    ]
  }
}

[/dm_code_snippet]
Let’s remember the weights:
1 → 2 (candidate1 weight)
2 → 1 (candidate2 weight)
3 → 1 (candidate3 weight)

 

Example 1: Personalize search weights

Project weights configuration:
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

similarity_tresholds:
    work_types.id:                     1.0
    employment_types.id:               2.0
    example.id:                        10.0

[/dm_code_snippet]
I would like to show an example based on Symfony 3.4 and FosElasticaBundle 5.1.1, but feel free to try with different stack (almost each major programming language has a great Elasticsearch library which supports mapping, queries and more).  
In this case, weights are defined globally in one of the parameter files in Symfony. But nothing stands in the way of moving this configuration to a database and attaching them to certain companies.
And how does it look in PHP?
We passed declared weights in the constructor. Then, in the class responsible for the manipulation of weights, we have a method for checking if we have defined weights that we can attach to certain search criteria.
At the end, we create a part of a search query with suitable weight to Elasticsearch query.
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

private array $filtersToBoost;
public function __construct(array $filtersToBoost)
{
    $this->filtersToBoost = $filtersToBoost;
}
private function applyBoostIfExists(string $filterName, BoolQuery $boolQuery):  BoolQuery
{
    if (array_key_exists($filterName, $this->filtersToBoost)) {
        $boolQuery->setBoost($this->filtersToBoost[$filterName]);
    }
    return $boolQuery;
}

[/dm_code_snippet]

In the results, we get a simple Elasticsearch query where:
– work type parameter has a weight = 1
– employment type parameter has a weight = 2.
It means that the employment type parameter is 2 times more important than the work type parameter. 
In practice, it looks just like this:
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

GET gs_application/application/_search
{
  "_source": [
    "fullname"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "profile.work_types",
            "query": {
              "bool": {
                "boost": 1,
               "must": [
                 {"terms": {
                   "profile.work_types.id": [
                     1
                   ]
                 }}
               ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "profile.employment_types",
            "query": {
              "bool": {
                "boost": 2,
                "must": [
                  {
                    "terms": {
                      "profile.employment_types.id": [
                        1
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

[/dm_code_snippet]
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

{
  "took" : 5,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 3.0,
    "hits" : [
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "78",
        "_score" : 3.0,
        "_source" : {
          "fullname" : "surname1 candidate1"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "80",
        "_score" : 2.0,
        "_source" : {
          "fullname" : "surname3 candidate3"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "79",
        "_score" : 1.0,
        "_source" : {
          "fullname" : "surname2 candidate2"
        }
      }
    ]
  }
}

[/dm_code_snippet]
In result we get:
1 → score:3 (candidate1) user with employment type = 1 – score boosted
2 → score:2 (candidate3) user with employment type = 1 – score boosted
3 → score:1 (candidate2)
As we can see, candidates with employment type = 1 are scored higher. This example shows how can we manage search weights in a simple way.

 

Example 2: Personalize results with score functions

Search results in Elasticsearch are sorted by “score” value. If the personalization of weights isn’t good enough or doesn’t fit our needs, we have the option to multiply the score value of a record by the weight parameter and boost_mode.
Let’s say we’d like to see the records with employment type = 1 have their scores increased 4-times.
The Elasticsearch query would look like this:
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

GET gs_application/application/_search
{
  "_source": [
    "fullname"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "profile.work_types",
            "query": {
              "bool": {
                "boost": 2,
                "must": [
                  {
                    "terms": {
                      "profile.work_types.id": [
                        1
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "profile.employment_types",
            "query": {
              "function_score": {
                "query": {
                  "terms": {
                    "profile.employment_types.id": [
                      1
                    ]
                  }
                },
                "functions": [
                  {
                    "filter": {
                      "terms": {
                        "profile.employment_types.id": [
                          1
                        ]
                      }
                    },
                    "weight": 4
                  }
                ],
                "boost_mode": "multiply"
              }
            }
          }
        }
      ]
    }
  }
}

[/dm_code_snippet]
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

{
  "took" : 13,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 6.0,
    "hits" : [
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "78",
        "_score" : 6.0,
        "_source" : {
          "fullname" : "surname1 candidate1"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "80",
        "_score" : 4.0,
        "_source" : {
          "fullname" : "surname3 candidate3"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "79",
        "_score" : 2.0,
        "_source" : {
          "fullname" : "surname2 candidate2"
        }
      }
    ]
  }
}

[/dm_code_snippet]
We get:
1 → score: 6 (candidate1) – employment type = 1 – score boosted even more
2 → score: 4 (candidate3) – employment type = 1 – score boosted even more
3 → score: 2 (candidate2)

 

Example 3: Score script

An extension of the below functionality is an inline script – called painless scripting language. With that solution, we can personalize results based on the record we’ve stored in Elasticsearch.
If we want to have candidates who are looking for permanent job (employment type = 1) on the top of the list, then we can use the score script to boost those records 4 times. This is a different way to obtain similar results like we got in previous example, but here we have much more flexibility in manipulating score results for specific documents (records).
An example of an Elasticsearch query:
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

GET gs_application/application/_search
{
  "_source": [
    "fullname"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "profile.work_types",
            "query": {
              "bool": {
                "boost": 2,
                "must": [
                  {
                    "terms": {
                      "profile.work_types.id": [
                        1
                      ]
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "profile.employment_types",
            "query": {
              "function_score": {
                "query": {
                  "terms": {
                    "profile.employment_types.id": [
                      1
                    ]
                  }
                },
                "functions": [
                  {
                    "script_score": {
                      "script": {
                        "params": {
                          "multiplier":  4
                        },
                        "source": "def et = doc['profile.employment_types.id'].value; if (et == 1) {return _score * params.multiplier} else {return _score}"
                      }
                    }
                  }
                ],
                "boost_mode": "multiply"
              }
            }
          }
        }
      ]
    }
  }
}

[/dm_code_snippet]
[dm_code_snippet background=”yes” background-mobile=”yes” bg-color=”#eeeeee” theme=”dark” language=”php” wrapped=”no” copy-text=”Copy Code” copy-confirmed=”Copied”]

{
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 3,
    "max_score" : 6.0,
    "hits" : [
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "78",
        "_score" : 6.0,
        "_source" : {
          "fullname" : "surname1 candidate1"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "80",
        "_score" : 4.0,
        "_source" : {
          "fullname" : "surname3 candidate3"
        }
      },
      {
        "_index" : "gs_application",
        "_type" : "application",
        "_id" : "79",
        "_score" : 2.0,
        "_source" : {
          "fullname" : "surname2 candidate2"
        }
      }
    ]
  }
}

[/dm_code_snippet]
In results we get:
1 → score: 6 (candidate1) – employment type = 1 – score boosted
2 → score: 4 (candidate3) – employment type = 1 – score boosted
3 → score: 2 (candidate2)

 

Conclusion

To personalize search with Elasticsearch is pretty simple. I’d like to show how developers can create advanced search engines easily, based on customer needs. Those above examples are a great starting point for more complicated conditions.