Dart/Flutter package for using Elastic App Search through a simple API returning easy to handle objects

Overview

@hikeland https://dart.dev/ https://flutter.dev/

Dart/Flutter package for using Elastic App Search through a simple API returning easy to handle objects

Elastic Elastic

This package is a ready-to-use API for Elastic App Search.

⚠️ You need an active deployment on Elastic to use this service.

This package does not intend to learn you how Elastic App Search is working, it is just intended to help you make queries and manipulate results easily, assuming that you already know Elastic App Search principles.

Here is a simple example of how you can query your Elastic engine:

final service = ElasticAppSearch(
    endPoint: "https://localhost:5601", 
    searchKey: "search-soaewu2ye6uc45dr8mcd54v8",
);

ElasticResponse response = await service
  .engine("national-parks-demo")
  .query("parks")
  .filter("states", isEqualTo: "California")
  .filter("world_heritage_site", isEqualTo: true)
  .resultField("title")
  .resultField("description", snippetSize: 140)
  .page(1, size: 50)
  .get();

for (ElasticResult result in response.results) {
  final data = result.data;
  if (data != null) {
    print("${data["title"]}: ${data["description"]}");
  }
}

This example will query the parks containing parks in any field of the documents. The results will be filtering the parks based in California, with the flag world_heritage_site set to true. Only the title and a snippet of 140 chars of the description of the park will be returned by the query. We request the first page, limited to 50 documents.

Table of contents

ElasticAppSearch

Before any operation, you need to create an instance of ElasticAppSearch.

Param Type Description
endPoint String The URL of your end point
searchKey String The search key of your deployment

Both values are available in your deployment, when going to App Search then Credentials. Warning: use the search-key, not the private-key!

final service = ElasticAppSearch(
    endPoint: "https://localhost:5601", 
    searchKey: "search-soaewu2ye6uc45dr8mcd54v8",
);

ElasticEngine

All the queries must be sent to an engine. To make instantiating an engine easy, we created this syntax:

Type Description
String The name of your engine
final engine = service.engine("engine_name");

ElasticQuery

The only required parameter to instanciate a query is a string which is the word you are looking for through your documents.

πŸ” See https://www.elastic.co/guide/en/app-search/current/search.html

Type Description
String The keyword
final query = engine.query("query");

Precision

This setting is available through the query modifier .precision

The value of the precision parameter must be an integer between 1 and 11, inclusive. The range of values represents a sliding scale that manages the inherent tradeoff between precision and recall. Lower values favor recall, while higher values favor precision.

πŸ” See https://www.elastic.co/guide/en/app-search/current/search-api-precision.html

final query = query.precision(5);

Search filters

This setting is available through the query modifier .filter

This feature intends to filter documents that contain a specific field value. It's only available on text, number, and date fields.

πŸ” See https://www.elastic.co/guide/en/app-search/current/filters.html

Important: As for now, this object only handles "all" filters, which means that all the filters added to the query will be handled as a "AND" query. The other filters available, "or" and "not", will be added in a future release of the package.

Param Type Description
(unnamed) String The field name
isEqualTo dynamic The value that the field must match
whereIn List The field must match one of these values

Warning: You cannot use isEqualTo and whereIn on the same field at the same time, otherwise it will raise an exception.

final query = query.filter("field", isEqualTo: "value");
final query = query.filter("field", isEqualTo: true);
final query = query.filter("field", whereIn: ["value1", "value2"]);

Search fields

This setting is available through the query modifier .searchField

It will restrict a query to search only specific fields. Restricting fields will result in faster queries, especially for schemas with many text fields Only available within text fields.

Weight is given between 10 (most relevant) to 1 (least relevant).

πŸ” See https://www.elastic.co/guide/en/app-search/current/search-fields-weights.html

Param Type Description
(unnamed) String The field name
weight int (optionnal) The weight of the field in the query
final query = query
  .searchField("field1", weight: 8)
  .searchField("field2", weight: 3);

Result fields

This setting is available through the query modifier .resultField

The fields which appear in search results and how their values are rendered.

Raw is an exact representation of the value within a field. Snippet is a representation of the value within a field, where query matches are returned in a specific field and other parts are splitted, in order to user [RichText] to display the results and highlight the query matches.

πŸ” See https://www.elastic.co/guide/en/app-search/current/result-fields-highlights.html

Param Type Description
(unnamed) String The field name
rawSize int (optionnal) The length of the field value which is returned
snippetSize int (optionnal) The length of the snippet value which is returned
fallback bool (optionnal) If true, return the raw text field if no snippet is found. If false, only use snippets.
final query = query
  .resultField("field1", rawSize: 80)
  .resultField("field2", snippetSize: 80)
  .resultField("field3", rawSize: 80, snippetSize: 80, fallback: true);

ElasticResponse

The response object contains two parts, the meta in a ElasticResponseMeta object and the results in a list of ElasticResult objects.

πŸ” See https://www.elastic.co/guide/en/app-search/current/search.html#search-api-response-body

Param Type Description
meta ElasticResponseMeta Object delimiting the results meta data
results List Array of results matching the search

ElasticResponseMeta

An object containing information about the results, especially the pagination details in page.

Param Type Description
requestId String ID representing the request. Guaranteed to be unique
warnings List Array of warnings for the query
alerts List Array of alerts for your deployment
page ElasticMetaPage Object delimiting the pagination meta data

ElasticResponseMetaPage

Object delimiting the results meta data.

Param Type Description
current int Number representing the current page of results
size int Number representing the results per page
totalPages int Number representing the total pages of results
totalResults int Number representing the total results across all pages

ElasticResult

An object presenting a result to the query.

The data param is a map of the fields requested with the .searchResult modfifier. If this modifier was omitted, all the fields of the document are returned.

The snippets is a map of the snippets returned by the query, if requested with the .searchResult modfifier. By default, Elastic returns the snippets as HTML snippets. This package manipulates the result to return some stuff that can be handled by Flutter: an ElasticResultSnippet object.

Param Type Description
data Map A map of the raw data of the document
snippets Map A map of the snippets
meta ElasticResultMeta An object containing information about a given result

ElasticResultMeta

An object containing information about a given result.

Param Type Description
id String The document ID
engine String The engine name
score double The relevance of the result

ElasticResultSnippet

An object contaning the snippet of the result. If you don't want to display your search results with highlights on the matching keyword, just ignore textParts and highlights and use only fullText.

textParts and highlights can be used to build a RichText widget in Flutter, please look at the example of the package to have a concrete example.

Param Type Description
fullText String The full snippet
textParts List The snippet splitted in parts around the matched query
highlights List The words matching the query

Third party packages

This app uses some external librairies:

Credits

This package was originally created for my personnal needs but feel free to use it, it does not covers all the features available in Elastic App Search, but I will try to cover all the features over time.

I am not related to Elastic in any way, I am just a developer who needed to use this API and created this library to do so.

If you have questions, feel free to ask on Twitter.

LICENSE: MIT

You might also like...

This is a simple flutter prototype that can be used to search contacts on mobile phones.

flutter_contacts_example This is a simple prototype which allow us to search contacts. Getting Started This project is a starting point for a Flutter

Apr 20, 2022

Weather-App-Api- - Simple Realtime Weather App With Api

Weather-App-Api- - Simple Realtime Weather App With Api

music_app A new Flutter Weather App project. Getting Started // Ψ§ΩˆΩ„ Ψ­Ψ§Ψ¬Ω‡ ΨͺΨΉΩ…Ω„ en

Nov 11, 2022

A simple and easy to use Redis client for Dart

redis_dart A simple and minimalist Redis client for Dart See it in pub: https://pub.dev/packages/redis_dart and GitHub: https://github.com/gabrielpach

Dec 25, 2022

A simple easy to use Flutter DApp , which keeps a track of all your day to day transactions by using Ethereum blockchain in the background which in turn increases your credit score.

A simple easy to use Flutter DApp , which keeps a track of all your day to day transactions by using Ethereum blockchain in the background which in turn increases your credit score.

Sahayog A simple easy to use Flutter DApp , which keeps a track of all your day to day transactions by using Ethereum blockchain in the background whi

May 21, 2022

Flutter ShopApp, you can see products and their prices, categories and their products, search for a product, add to favorite, add to cart, sign in and sign up.

shop_app_2 A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you started i

Aug 7, 2022

A Flutter package that makes it easy to customize and work with your Flutter desktop app's system tray.

A Flutter package that makes it easy to customize and work with your Flutter desktop app's system tray.

system_tray A Flutter package that that enables support for system tray menu for desktop flutter apps. on Windows, macOS and Linux. Features: - Modify

Dec 30, 2022

A Flutter package that makes it easy to customize and work with your Flutter desktop app window.

A Flutter package that makes it easy to customize and work with your Flutter desktop app window.

bitsdojo_window A Flutter package that makes it easy to customize and work with your Flutter desktop app window on Windows, macOS and Linux. Watch the

Dec 27, 2022

simple movies app with flutter, and using movie api

simple movies app with flutter, and using movie api

movies A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Dec 26, 2021

Movies - A simple movie app using TMDB API(developers.themoviedb.org)

Movies - A simple movie app using TMDB API(developers.themoviedb.org)

movies A simple movie app using TMDB API(developers.themoviedb.org) Screenshot M

Nov 29, 2022
Comments
  • Print statements in package

    Print statements in package

    This package is great for using elastic app search.

    Noticed that there are print statements in the package (v 0.3.0) code which are not controlled from app using this package.

    Two ways to solve it -

    1. Remove print statements
    2. Make it configurable from app while defining elastic service or while querying.

    Files with print statements -

    lib/src/service.dart lib/src/result.dart

    opened by XenLabsNikhil 3
  • Number Range Filter type casting in Elastic Request

    Number Range Filter type casting in Elastic Request

    Whenever I attempt to add a range filter to a "number" result field, the resultant query takes my input (a double) and converts to a string.

    Example:

    Flutter end

    ElasticAppSearch(...)
      .engine('example')
      .query('')
      .filter('price',
        isGreaterThanOrEqualTo: 80.0, isLessTan: 100.0);
      .get();
    

    Request as displayed in Kibana

    {
      "query": "",
      "page": {
        "size": 20,
        "current": 1
      },
      "filters": {
        "all": [
          {
            "price": {
              "from": "80.0",
              "to": "100.0"
            }
          }
        ],
        "none": [],
        "any": []
      }
    }
    

    Response

    {
      "errors": [
        "Filters 'from' must be a number for field: price",
        "Filters 'to' must be a number for field: price"
      ]
    }
    

    I would also like to note that if the input is changed to an int value, then null is produced for the price filter section of the query.

    Example:

    Flutter end

    ElasticAppSearch(...)
      .engine('example')
      .query('')
      .filter('price',
        isGreaterThanOrEqualTo: 80, isLessTan: 100);
      .get();
    

    Request as displayed in Kibana

    {
      "query": "",
      "page": {
        "size": 20,
        "current": 1
      },
      "filters": {
        "all": [
          {
            {
              "price": null
            }
          }
        ],
        "none": [],
        "any": []
      }
    }
    

    Response

    {
      "errors": [
        "Filters contains invalid value for field: price; must be a number, an array of numbers, or a range object with `to` and/or `from` keys"
      ]
    }
    

    I tried to debug this in your src code, but it does seem you are casting "from" and "to" as double. I'm not sure what the issue is. Is there something I'm missing on my end? Otherwise great package, very useful in my case :)

    opened by Asmith9555 2
  • ElasticQuery systematically raises an assert error due to queryPrecision parameter.

    ElasticQuery systematically raises an assert error due to queryPrecision parameter.

    ElasticQuery systematically raises an assert error due to queryPrecision parameter.

    flutter: 'package:elastic_app_search[/elastic_app_search.freezed.dart]()': Failed assertion: line 296 pos 13: 'queryPrecision != null &&
    package:elastic_app_search/elastic_app_search.freezed.dart:296
                    (queryPrecision < 1 || queryPrecision > 11)': The value of the precision parameter must be an integer between 1 and 11, inclusive.
    
    bug 
    opened by julienlebren 1
Owner
Julien Le Bren
Developer since 2000 // PHP/Javascript/MySQL in the early years // Objective-C since 2010 // More recently: Swift, SwiftUI // Currently hardly using Flutter πŸ’™
Julien Le Bren
Winner (2nd Place) of the all-India UIDAI Hackathon 2021. The project contains a Verifier and a Resident application built to authenticate users through Aadhaar API's

Second Place Winner for the UIDAI Hackathon 2021 by Team 202 ACCEPTED Theme 2 : Problem Statement 4 100% Authentication success in Rural India Importa

Omkar Prabhune 13 Dec 30, 2022
Flutter Radio Player, A Plugin to handle streaming audio without a hassle

Flutter radio plugin handles a single streaming media preciously. This plugin was developed with maximum usage in mind. Flutter Radio player enables S

Sithira Munasinghe 104 Dec 27, 2022
✈️ A tidy utility to handle offline/online connectivity like a Boss

✈️ Flutter Offline A tidy utility to handle offline/online connectivity like a Boss. It provides support for both iOS and Android platforms (offcourse

Jeremiah Ogbomo 845 Jan 2, 2023
Quiz App is cross-platform mobile app, that allows you to test your knowledge on various technologies through quizzes. It's built with Flutter & Dart

Quiz App is cross-platform mobile app, that allows you to test your knowledge on various technologies through quizzes. It's built with Flutter & Dart

RΓ©gis 6 Sep 19, 2022
Application that consumes the Movie Database (TMDB) api to show and search any kind of movie with its actors.

# cartelera A new Flutter project. ## Getting Started This project is a starting point for a Flutter application. A few resources to get you start

null 2 Jan 11, 2022
App for sending ssh requests. Wake on Lan through ssh

wakeonwears WakeOnLan through ssh Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

Sergey Latu 1 Oct 15, 2021
A web dashboard that allows you to monitor your Chia farm and sends notifications when blocks are found and new plots are completed through a discord bot. It can link multiple farmers/harvesters to your account.

farmr A web dashboard that allows you to monitor your Chia farm and sends notifications when blocks are found and new plots are completed through a di

Gil Nobrega 261 Jan 2, 2023
Helping navigate through maps to prefer road-way.

pothole-detector Detecting potholes using a smartphone app, & display the data to users over maps (google or open-street) through a app. In future, th

DEVSTRONS' 7 Dec 15, 2022
Compress videos, remove audio, manipulate thumbnails, and make your video compatible with all platforms through this lightweight and efficient library.

video_compress Compress videos, remove audio, manipulate thumbnails, and make your video compatible with all platforms through this lightweight and ef

Jonny Borges 172 Dec 31, 2022
A cryptocurrency, crypto-currency, or crypto is a digital currency designed to work as a medium of exchange through a computer network that is not reliant on any central authority

A cryptocurrency, crypto-currency, or crypto is a digital currency designed to work as a medium of exchange through a computer network that is not reliant on any central authority, such as a government or bank, to uphold or maintain it.

Prashant Kumar Singh 10 Dec 3, 2022