Giter Club home page Giter Club logo

app-search-javascript's Introduction

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!

app-search-javascript's People

Contributors

goodroot avatar jasonstoltz avatar joemcelroy avatar jonasll avatar kbazsi avatar marshalium avatar miguelgrinberg avatar richkuz avatar tehsven avatar yakhinvadim avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

app-search-javascript's Issues

Search query with minus -

Search queries with minus sign dont seem to work in Elastic App Search.

I need to be able to search "-95" and get all the SKU that contain "-95" in the SKU number but it doesn't work with the current setup. Is there a workaround?

add contributing.md

I would like to create a file contributing.md and add following -
1.Difference between GIT and GITHUB
2.How to clone,fork repository
3.How to create a branch and then use git push to push to repo
4.Create a PR
5.Squash commits in a single issue into one
6, Updating the forked and local repo as the updations are made in the upstream

Cookie set without the 'SameSite' attriubute

This issue is prompting multiple client warnings.

Using v7.8.0

A cookie associated with a cross-site resource at http://swiftype.com/ was set without the SameSiteattribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set withSameSite=NoneandSecure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

CORS on https

Hello and thanks in advance for any information you might share.

I have a repo built around this which was working fine when going from http to http API Endpoint... but when deployed into https it's run into CORS issues. Have tried pretty much everything at this point. Figured I'd check in and see if anyone can sanity check the concept in general - is there any reason why this wouldn't work over https? Should I be thinking about this more as a "public key" search client?

I don't want to get too deep into sharing code yet as I'd have to redact but if anyone can sanity check me on whether it's an appropriate use of this for https, I'd appreciate it.

Thank you!

Geo-Bounding Box Query in App Search

Is your feature request related to a problem? Please describe.
We need to Geo-Bounding Box Query to filter results in a certain area and would like to use App Search to optimize our search experience.

Describe the solution you'd like
Addition of Geo-Bounding Box Query functionality to App Search api.

Describe alternatives you've considered
We've built our search using ElasticSearch api and have implemented Geo-Bounding Box Query, however, we'd like to use App Search for the search tuning features and ease of use .

Typo in README.md

The readme has a typo, the link to the FETCH_API documentation misses the last I (capital i).
Also the Query Suggestion example declares the options variable but does not use it.

I created a pull request to address these.

Erroneous 100 Document Limit?

Hello, I'm trying to determine the source of a given issue. We've built a working search interface as part of our application in React Native using ElasticAppSearch and this plugin. However, an issue seems to arise when we try to access documents beyond a certain point, and at a much lower level than the documentation on ElasticAppSearch would suggest.

If we call for the size of a given search request to exceed 100 documents, it always, invariably, returns just up to 100. All further requests beyond that return no results. We know for certain there are more documents than that in our engine, and have even confirmed this by checking against total results. But for whatever reason, that 100 documents limit is resolutely in place.

Do you all have any insight into this problem? Thank you.

Disjunctive facets may break when used with signed search keys

Hello! I'm having trouble to make disjunctive facets work with signed search keys.

I think it's related to this: elastic/search-ui#347

On this line, I see that we are cleaning up request filters, but on my case filters are still sent this way:
Screenshot from 2020-06-02 11-34-24

Which seems to cause some kind of issue with AppSearch using signed search keys.

  "alerts":[{"code":5001,"message":"Degraded search results","link":"https://swiftype.com/documentation/app-search/alerts#5001"}]

What I tried:

  • If I remove filters on that request it works even with a signed search key
  • Also if I change the signed search key to a normal search key, it also works.

One last thing
My search key only applies one filter:
Screenshot from 2020-06-03 15-32-39

Any help is much appreciated!!
Thanks

v8.6+ unable to import and build with Vite

When upgrading from v8.5.1 to v8.6 or v8.7 my builds start failing with Vite.

I get the following error:

Failed to resolve entry for package "@elastic/app-search-javascript". The package may have incorrect main/module/exports specified in its package.json

Any ideas?

Again I've narrowed it down to upgrading it past v8.5.1.

Allow for full url specification

There are cases in which app search is being an API gateway or reverse proxy that benefits from allowing the consumer of the app-search client to specify what the end point should be.

This recently came up on a search-ui implementation where just the production environment was going to be behind a API gateway. This would require implementing a custom handler/middleware in search-ui which would be better to simply have the string concatenation for the endpoint overwritten or specified by the consumer of the SDK.

https://github.com/elastic/app-search-javascript/blob/master/src/client.js#L50

disable ssl

Hello, can I add SSL verify to false for the client request to the app search server through HTTPS?

Allow GET method for Queries to App Search API

The App Search documentation states that one can use a GET or POST request when accessing /api/as/v1/engines/{ENGINE_NAME}/search for a search query. However, app-search-javascript only allows you to utilize a POST request for this.

POST requests are meant for unique non-repeatable actions, while GET requests are intended for repeatable actions without side effects. An example of how this plays out in the real world is if you submit a POST request on page load, then attempt to refresh the page, Google Chrome will warn you with an alert pop-up asking you to "Conform Form Resubmission".

The above example can occur in @elastic/search-ui when utilizing "alwaysSearchOnInitialLoad: true". Because @elastic/search-ui utilizes @elastic/app-search-javascript as a dep, and @elastic/app-search-javascript uses POST requests by default, when alwaysSearchOnInitialLoad: true then the page will fire a POST request, and attempting to refresh the page or navigate back to it will trigger the "Confirm Form Resubmission" alert, even though the user took no action.

We should supply an option so that people utilizing the @elastic/app-search-javascript library can make the choice for themselves which method to use, based on their implementation requirements.

Support filters in query suggestion

We have a use case where we would like to add filters in query suggestion (e.g. filter out disabled products). Elastic Search itself supports the use case, however, app search doesn't support filters yet. Could you add the support? Thanks in advance!

App search query suggestion doc - https://www.elastic.co/guide/en/app-search/current/query-suggestions-guide.html
Elastic Search suggester doc - https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html

Indexing documents using client

Hi there,
I am creating an app using Elastic App Search and I am using app-search-javascript. I want to index documents in app search engine. Is there any way to do it using the client?

Sort using

Hi,
I am using the sort attribute on published_at (date type) for documents.
But it looks like if the document doesn't have published_at attribute, the sorting won't display the document:

"sort" :[
        { "published_at" : "desc"} 
 ]

It should sort the documents ร  the end even the attributes is missing no ?

Retrieve selected facets first with disjunctiveFacets

Let's say we are using the facet with the following options:

const options = {
  facets: {
    location: [{ type: 'value', size: 6 }],
  },
  disjunctiveFacets: ['location'],
  filters: { location: ['Canada', 'United States']},
};
client
  .search('yoga', options);
  .then(({ info }) => {
    console.log(info.facets.location);
  });

If the location Canada is not in the first 6 most popular facet results for this query, it is not included in info.facets.location. Only the 6 most populars are accessible. However, I can see we retrieve this data from the request that is not Facet-Only (since it returns only the two facets that we used to filter).

If we use the facets results to display checkboxes (with multiple selection active), it is a problem since the Canada option will not be shown, and then cannot be remove from the filters. We need to "cache" that selected value, and then display it without it's count.

I don't know if this should be implemented at a endpoint level, but I think the active filters should be returned as the first values when retrieving facet values, so that the UI can be implemented out-of-the-box. Even if they are empty (count = 0). That way, it will be easier to implement a UI based on them.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.