Try   HackMD

Elastic App Search 前端連接

Elastic App Search 透過前端連接來執行搜尋的動作,本文僅示範JavaScript連接


一、支援的客戶端

  • JavaScript
  • Node.js
  • PHP
  • Python
  • Ruby

二、JavaScript 連接

  1. 使用CDN的方式引入js檔

    ​​​​<script src="https://cdn.jsdelivr.net/npm/@elastic/app-search-javascript@7.8.0/dist/elastic_app_search.umd.js"></script>
  2. js用法範例

    ​​​​var client = ElasticAppSearch.createClient({ ​​​​ searchKey: "your search key", ​​​​ endpointBase: "your endpoint", ​​​​ engineName: "your engineName" ​​​​ }); ​​​​var options = { ​​​​ search_fields: { name_zh: {} }, ​​​​ result_fields: { id: { raw: {} }, ​​​​ name_zh: { raw: {} }, ​​​​ selling_price:{raw:{}} } ​​​​ }; ​​​​ client ​​​​ .search("貓砂", options) ​​​​ .then(resultList => { ​​​​ resultList.results.forEach(result => { ​​​​ console.log(`id: ${result.getRaw("id")} ​​​​ raw: ${result.getRaw("name_zh")} : ​​​​ ${result.getRaw("selling_price")}`); ​​​​ }); ​​​​ }) ​​​​ .catch(error => { ​​​​ console.log(`error: ${error}`); ​​​​ });
  3. 完整檔案

    ​​​​<!DOCTYPE html> ​​​​<html lang="en"> ​​​​<head> ​​​​ <meta charset="UTF-8"> ​​​​ <meta http-equiv="X-UA-Compatible" content="IE=edge"> ​​​​ <meta name="viewport" content="width=device-width, initial-scale=1.0"> ​​​​ <script ​​​​ src="https://cdn.jsdelivr.net/npm/@elastic/app-search-javascript@7.8.0/dist/elastic_app_search.umd.js"></script> ​​​​ <title>Document</title> ​​​​</head> ​​​​<body> ​​​​</body> ​​​​<script> ​​​​ var client = ElasticAppSearch.createClient({ ​​​​ searchKey: "your search key", ​​​​ endpointBase: "your endpoint", ​​​​ engineName: "your engineName" ​​​​ }); ​​​​ var options = { ​​​​ search_fields: { name_zh: {} }, ​​​​ result_fields: { id: { raw: {} }, name_zh: { raw: {} }, selling_price:{raw:{}} } ​​​​ }; ​​​​ client ​​​​ .search("貓砂", options) ​​​​ .then(resultList => { ​​​​ resultList.results.forEach(result => { ​​​​ console.log(`id: ${result.getRaw("id")} raw: ${result.getRaw("name_zh")} : ${result.getRaw("selling_price")}`); ​​​​ }); ​​​​ }) ​​​​ .catch(error => { ​​​​ console.log(`error: ${error}`); ​​​​ }); ​​​​</script> ​​​​</html>
  4. 搜尋結果

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

回傳結果第一條是在Elastic App Search 設定 Curation 的結果

參考資料

參考資料的CDN是錯誤的

需要使用

https://cdn.jsdelivr.net/npm/@elastic/app-search-javascript@7.8.0/dist/elastic_app_search.umd.js

或者到 jsDelivr

查詢最新版本