All Projects → elastic → app-search-javascript

elastic / app-search-javascript

Licence: Apache-2.0 license
Elastic App Search Official JavaScript Client

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to app-search-javascript

app-search-magento
A first party module to integrate Elastic App Search in Magento 2.
Stars: ✭ 25 (-55.36%)
Mutual labels:  elastic, swiftype, elastic-app-search
app-search-python
Elastic App Search Official Python Client
Stars: ✭ 34 (-39.29%)
Mutual labels:  elastic, swiftype, elastic-app-search
swiftype-wordpress
Elastic Site Search (Swiftype) Wordpress Plugin for full-text search
Stars: ✭ 26 (-53.57%)
Mutual labels:  elastic, swiftype
enterprise-search-php
Elastic Enterprise Search Official PHP Client
Stars: ✭ 20 (-64.29%)
Mutual labels:  elastic, elastic-app-search
app-search-flask-app
This is an example of a Python Flask app with Elasticsearch/ Elastic App Search with respective Python Clients
Stars: ✭ 17 (-69.64%)
Mutual labels:  elastic, elastic-app-search
Quicklogger
Library for logging on files, console, memory, email, rest, eventlog, syslog, slack, telegram, redis, logstash, elasticsearch, influxdb, graylog, Sentry, Twilio, ide debug messages and throw events for Delphi/Firemonkey/freepascal/.NET (Windows/Linux/OSX/IOS/Android).
Stars: ✭ 137 (+144.64%)
Mutual labels:  elastic
Elastix
A simple Elasticsearch REST client written in Elixir.
Stars: ✭ 231 (+312.5%)
Mutual labels:  elastic
Sigmaui
SIGMA UI is a free open-source application based on the Elastic stack and Sigma Converter (sigmac)
Stars: ✭ 123 (+119.64%)
Mutual labels:  elastic
Elastic
Elastic Stack (6.2.4) 을 활용한 Dashboard 만들기 Project
Stars: ✭ 121 (+116.07%)
Mutual labels:  elastic
jmx-monitoring-stacks
No description or website provided.
Stars: ✭ 170 (+203.57%)
Mutual labels:  elastic
elasticscout
ElasticScout is an optimized Laravel Scout driver for Elasticsearch 7.1+
Stars: ✭ 64 (+14.29%)
Mutual labels:  elastic
Fleetx
Paddle Distributed Training Extended. 飞桨分布式训练扩展包
Stars: ✭ 196 (+250%)
Mutual labels:  elastic
Tgrefreshoc
弹簧、橡皮筋下拉刷新控件,类似QQ下拉刷新效果,同时支持其他样式
Stars: ✭ 149 (+166.07%)
Mutual labels:  elastic
Laravel Aws Eb
Ready-to-deploy configuration to run Laravel on AWS Elastic Beanstalk.
Stars: ✭ 247 (+341.07%)
Mutual labels:  elastic
Elastic Stack
Aprenda Elasticsearch, Logstash, Kibana e Beats do jeito mais fácil ⭐️
Stars: ✭ 135 (+141.07%)
Mutual labels:  elastic
simplx
C++ development framework for building reliable cache-friendly distributed and concurrent multicore software
Stars: ✭ 61 (+8.93%)
Mutual labels:  elastic
Icinga2
Icinga is a monitoring system which checks the availability of your network resources, notifies users of outages, and generates performance data for reporting.
Stars: ✭ 1,670 (+2882.14%)
Mutual labels:  elastic
Elastic Charts
📊 Elastic Charts library
Stars: ✭ 191 (+241.07%)
Mutual labels:  elastic
datalogger
DataLogger foi projetado para ser uma biblioteca simples de log com suporte a vários providers.
Stars: ✭ 46 (-17.86%)
Mutual labels:  elastic
Docker Elastic Stack
ELK Stack Dockerfile
Stars: ✭ 175 (+212.5%)
Mutual labels:  elastic

Elastic App Search Logo

CircleCI buidl

A first-party JavaScript client for building excellent, relevant search experiences with Elastic App Search.

Contents


Getting started 🐣

Install from a CDN

The easiest way to install this client is to simply include the built distribution from the jsDelivr CDN.

<script src="https://cdn.jsdelivr.net/npm/@elastic/[email protected]/dist/elastic_app_search.umd.js"></script>

This will make the client available globally at:

window.ElasticAppSearch;

Install from NPM

This package can also be installed with npm or yarn.

npm install --save @elastic/app-search-javascript

The client could then be included into your project like follows:

// CommonJS
var ElasticAppSearch = require("@elastic/app-search-javascript");

// ES
import * as ElasticAppSearch from "@elastic/app-search-javascript";

Versioning

This client is versioned and released alongside App Search.

To guarantee compatibility, use the most recent version of this library within the major version of the corresponding App Search implementation.

For example, for App Search 7.3, use 7.3 of this library or above, but not 8.0.

If you are using the SaaS version available on swiftype.com of App Search, you should use the version 7.5.x of the client.

Browser support

The client is compatible with all modern browsers.

Note that this library depends on the Fetch API.

This is not supported by Internet Explorer. If you need backwards compatibility for Internet Explorer, you'll need to polyfill the Fetch API with something like https://github.com/github/fetch.

Usage

Setup: Configuring the client and authentication

Using this client assumes that you have already an instance of Elastic App Search up and running.

The client is configured using the searchKey, endpointBase, and engineName parameters.

var client = ElasticAppSearch.createClient({
  searchKey: "search-mu75psc5egt9ppzuycnc2mc3",
  endpointBase: "http://127.0.0.1:3002",
  engineName: "favorite-videos"
});

* Please note that you should only ever use a Public Search Key within Javascript code on the browser. By default, your account should have a Key prefixed with search- that is read-only. More information can be found in the documentation.

Swiftype.com App Search users:

When using the SaaS version available on swiftype.com of App Search, you can configure the client using your hostIdentifier instead of the endpointBase parameter. The hostIdentifier can be found within the Credentials menu.

var client = ElasticAppSearch.createClient({
  hostIdentifier: "host-c5s2mj",
  searchKey: "search-mu75psc5egt9ppzuycnc2mc3",
  engineName: "favorite-videos"
});

List of configuration options:

Option Required Description
hostIdentifier No Your Host Identifier, should start with host-. Required unless explicitly setting endpointBase
searchKey No Your Public Search Key. It should start with search-.

NOTE: This is not technically required, but in 99% of cases it should be provided. There is a small edge case for not providing this, mainly useful for internal App Search usage, where this can be ommited in order to leverage App Search's session based authentication.
engineName Yes
endpointBase No Overrides the base of the App Search API endpoint completely. Useful when proxying the App Search API, developing against a local server, or a Self-Managed or Cloud Deployment. Ex. "http://localhost:3002"
cacheResponses No Whether or not API responses should be cached. Default: true.
additionalHeaders No An Object with keys and values that will be converted to header names and values on all API requests

API Methods

This client is a thin interface to the Elastic App Search API. Additional details for requests and responses can be found in the documentation.

Searching

For the query term lion, a search call is constructed as follows:

var options = {
  search_fields: { title: {} },
  result_fields: { id: { raw: {} }, title: { raw: {} } }
};

client
  .search("lion", options)
  .then(resultList => {
    resultList.results.forEach(result => {
      console.log(`id: ${result.getRaw("id")} raw: ${result.getRaw("title")}`);
    });
  })
  .catch(error => {
    console.log(`error: ${error}`);
  });

Note that options supports all options listed here: https://swiftype.com/documentation/app-search/guides/search.

In addition to the supported options above, we also support the following fields:

Name Type Description
disjunctiveFacets Array[String] An array of field names. Every field listed here must also be provided as a facet in the facet field. It denotes that a facet should be considered disjunctive. When returning counts for disjunctive facets, the counts will be returned as if no filter is applied on this field, even if one is applied.
disjunctiveFacetsAnalyticsTags Array[String] Used in conjunction with the disjunctiveFacets parameter. Queries will be tagged with "Facet-Only" in the Analytics Dashboard unless specified here.

Response

The search method returns the response wrapped in a ResultList type:

ResultList {
  rawResults: [], // List of raw `results` from JSON response
  rawInfo: { // Object wrapping the raw `meta` property from JSON response
    meta: {}
  },
  results: [ResultItem], // List of `results` wrapped in `ResultItem` type
  info: { // Currently the same as `rawInfo`
    meta: {}
  }
}

ResultItem {
  getRaw(fieldName), // Returns the HTML-unsafe raw value for a field, if it exists
  getSnippet(fieldName) // Returns the HTML-safe snippet value for a field, if it exists
}

Query Suggestion

var options = {
  size: 3,
  types: {
    documents: {
      fields: ["name"]
    }
  }
};

client
  .querySuggestion("cat", options)
  .then(response => {
    response.results.documents.forEach(document => {
      console.log(document.suggestion);
    });
  })
  .catch(error => {
    console.log(`error: ${error}`);
  });

Multi Search

It is possible to run multiple queries at once using the multiSearch method.

To search for the term lion and tiger, a search call is constructed as follows:

var options = {
  search_fields: { name: {} },
  result_fields: { id: { raw: {} }, title: { raw: {} } }
};

client
  .multiSearch([{ query: "node", options }, { query: "java", options }])
  .then(allResults => {
    allResults.forEach(resultList => {
      resultList.results.forEach(result => {
        console.log(
          `id: ${result.getRaw("id")} raw: ${result.getRaw("title")}`
        );
      });
    });
  })
  .catch(error => {
    console.log(`error: ${error}`);
  });

Clickthrough Tracking

client
  .click({
    query: "lion",
    documentId: "1234567",
    requestId: "8b55561954484f13d872728f849ffd22",
    tags: ["Animal"]
  })
  .catch(error => {
    console.log(`error: ${error}`);
  });

Clickthroughs can be tracked by binding client.click calls to click events on individual search result links.

The following example shows how this can be implemented declaratively by annotating links with class and data attributes.

document.addEventListener("click", function(e) {
  const el = e.target;
  if (!el.classList.contains("track-click")) return;

  client.click({
    query: el.getAttribute("data-query"),
    documentId: el.getAttribute("data-document-id"),
    requestId: el.getAttribute("data-request-id"),
    tags: [el.getAttribute("data-tag")]
  });
});
<a
  href="/items/1234567"
  class="track-click"
  data-request-id="8b55561954484f13d872728f849ffd22"
  data-document-id="1234567"
  data-query="lion"
  data-tag="Animal"
>
  Item 1
</a>

Running tests

The specs in this project use node-replay to capture responses.

The responses are then checked against Jest snapshots.

To capture new responses and update snapshots, run:

nvm use
REPLAY=record npm run test -u

To run tests:

nvm use
npm run test

Development

Node

You will probably want to install a node version manager, like nvm.

We depend upon the version of node defined in .nvmrc.

To install and use the correct node version with nvm:

nvm install

Dev Server

Install dependencies:

nvm use
npm install

Build artifacts in dist directory:

# This will create files in the `dist` directory
npm run build

Add an index.html file to your dist directory

<html>
  <head>
    <script src="elastic_app_search.umd.js"></script>
  </head>
  <body>

  </body>
</html>

Run dev server:

# This will serve files in the `dist` directory
npm run dev

Navigate to http://127.0.0.1:8080 and execute JavaScript commands through the browser Dev Console.

Build

nvm use
npm run build

Publish

nvm use
npm run publish

FAQ 🔮

What if I need write operations?

App Search has a first-party Node.js client which supports write operations like indexing.

Where do I report issues with the client?

If something is not working as expected, please open an issue.

Where can I learn more about App Search?

Your best bet is to read the documentation.

Where else can I go to get help?

You can checkout the Elastic App Search community discuss forums.

Contribute 🚀

We welcome contributors to the project. Before you begin, a couple notes...

License 📗

Apache 2.0 © Elastic

Thank you to all the contributors!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].