信同数范范范读范辛范范范范范范辛范辛范范辛范范辛辛辛信范辛 [英] iOS Firebase Flashlight/ElasticSearch Heroku Setup using Node.JS

查看:287
本文介绍了信同数范范范读范辛范范范范范范辛范辛范范辛范范辛辛辛信范辛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Swift中用Firebase后端构建一个iOS应用程序。我需要高级搜索选项为我的应用程序。我被告知我应该通过这个github链接使用Flashlight / ElasticSearch https://github.com/firebase/flashlight

假设我的应用名称是SneakerSearch,而我的

  Firebase Project_ID is-sneakersearch-az12 
Firebase Web_API_Key is-abc123XYZ000 ...
Firebase App_Url is-gs://sneakersearch-az12.appspot.com

由于我是Heroku和Node.js的新手,我需要一些建议。我以前从来没有学过,但我已经安装了Heroku工具带,并完成了sudo gem heroku install。



我列出了github的方向/步骤和我为每个方向采取的步骤。我需要帮助:1,4,5,6,9,10,12和15。

  1.安装并运行ElasticSearch或通过Heroku添加盆景服务

1。我在Heroku上建立了一个账户。


$ b $ 1.问:我需要创建我的应用程序的名字,并在设置我的Heroku帐户之后进行部署我等到第9步?

  2.git克隆https://github.com/firebase/flashlight 

2.将上面的代码复制到iOS应用程序的项目文件夹中

  3.npm install 

3.在提示符I首先我运行npm init,然后运行npm install。

$ p $ 4。编辑config.js(见上面的注释,你必须至少设置FB_URL和FB_SERVICEACCOUNT)

问题:什么是FB_SERVICEACCOUNT?我正在使用Firebase 3,但无法在控制台的服务帐户中找到任何内容。这是另一个Firebase帐户,我必须使用node.js设置我的项目,除了我已经做了Firebase的swift项目吗?



4B.-问题:我在哪里编辑config.js并将我的FB_URL和FB_SERVICEACCOUNT设置为?这应该是在我的package.json文件?

$ p $ 5.node app.js(运行应用程序)

5.-问题:在终端中,我运行了node app.js并得到throw err; ^。为什么我得到这个错误?

  6.curl -X POST http:// localhost:9200 / firebase 

6.-问题:这是干什么的?

  7.cd手电筒

7.切换到手电筒目录

  8.heroku登入



登录到Heroku

  9.heroku创建(添加heroku到项目)
9A-QUESTION:当我第一次在Heroku账户时,我应该用我的应用程序的名字创建一个新的应用程序,并部署它使用它列出的git指令?如果我不应该这样做,一开始会运行heroku创建管理该过程对我来说?

9B-问题:我只是运行heroku创建或做我运行heroku创建-app的名字 - 在这里?

pre $ 10.heroku addons:添加bonsai(安装盆景)

10.-问题:我需要在Bonasi.io创建一个帐户并在此步骤之前安装它这为我设立了一个盆景帐户?

  11.heroku配置(检查盆景实例信息并复制新的BONSAI_URL  - 您将需要它后来)

11.我想这个问题将取决于步骤#10。 b
$ b

  12.heroku config:set FB_NAME =< instance> FB_TOKEN = LT;令牌gt; 中(声明环境变量)

12.-问:什么是Firebase TOKEN?这是我的Web_API_Key,App_URL或Project_ID?在我的Firebase控制台中找不到特定于令牌的任何内容。我使用的是Firebase 3。
$ b

  13.git add config.js(更新)
git commit -m配置盆景

13。提交信息

  14.git push heroku master(部署到heroku)

14。推到掌握

$ $ p $ 15.heroku ps:scale worker = 1(启动dyno worker)

解决方案

这是一个2部分的答案,第一部分是通过Github的方向,并在第19步结束。第二部分扩展了更多的信息,不适合第一部分,它将从第19步开始详细。我将不得不添加到另一个问题,并将其链接到此。



以下是列出的 Github 步骤为了。仅供参考,我保留原来的步骤与原来的 Github作者列出了他们,但在下面我放了一大堆子步骤,每个子步骤下面有详细的解释和指导。 p>

假设您已经创建了一个 Firebase 项目并获得了您的 GoogleService-Info.plist file

打开 GoogleService-Info.plist 文件。以下变量来自 Github路线 GoogleService-Info.plist键相关
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
-FB_TOKEN和你的API_KEY是一样的

所以
$ b如果你的PROJECT_ID是sneakersearch-az12那么你的FB_NAME是sneakersearch-az12
如果你的DATABASE_URL是https://sneakersearch-az12.firebaseio.com那么你的FB_URL是https://sneakersearch-az12.firebaseio.com
如果你的API_KEY是0012abc789xyz00019那么你的FB_TOKEN是0012abc789xyz00019

//这些不在你的GoogleService-Info.plist里面,但是你稍后会遇到它们
-FB_SERVICEACCOUNT属于从你的项目的Firebase下载一个json文件安慰。您需要转到步骤3B中显示的服务帐户页面
-clientEmail与您的Firebase服务帐户相同。您可以通过FB控制台从未知文件或服务帐户页面获取此文件,并且在步骤3D和3B中进行了展示。
-privateKey与private_key相同,但此密钥不是您的API_KEY,而是密钥即在SERVICE ACCOUNTS页面的未知文件中。它看起来像这样:----- BEGIN PRIVATE KEY ----- \\\
CYchgacopuyvpc017246t124087t6hpUTYVPUSVDPUCHVEpcl889ljbsiugr4ygrphvuygpuy ... mutli-lines ... \\\
----- END PRIVATE KEY ----- \\\
。同样在步骤3B中展示

在每个 Github 一步我有意见,然后指示。在我使用下面的值的方向内,应该使用项目的值。因此,对于步骤示例,我将使用这些

  // GoogleService-Info.plist 
PROJECT_ID --- aka - FB_NAME:sneakersearch-az12
DATABASE_URL-aka - FB_URL:https: //sneakersearch-az12.firebaseio.com
API_KEY ------又名 - FB_TOKEN:0012abc789xyz00019
// FB服务帐户信息
Firebase服务帐户 - 又名 - 客户端电子邮件: firebase-admin-81772@sneakersearch-az12.iam.gserviceaccount.com //这是您创建Firebase项目后自动生成的
// Heroku和Bonsai信息
Heroku实例名称 - 又名 - Heroku App Name:sneakersearchinstanceAtoZ
BONASI_URL --aka - 盆景群集网址:https:// abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net


$ b

Swift Data Model:(这将与步骤19中的映射对象相匹配)

  class运动鞋:NSObject {
var sneakercondition:String?
var sneakername:String?





$ b使用文件路径将数据发送到Firebase和 searchSnkPath


  @IBOutlet weak var conditionTextField:UITextField!/ em>是一个单独的文件路径,盆景将运行它的搜索: 
@IBOutlet弱var nameTextField:UITextField!

var dbRef:FIRDatabaseReference!
let userID = FIRAuth.auth()?。currentUser?.uid

重写func viewDidLoad(){
super.viewDidLoad()
self.dbRef = FIRDatabase .database()。reference()
}

@IBAction func postDataButton(){

var dict = [String:AnyObject]()
dict.updateValue(conditionTextField.text !, forKey:sneakercondition)
dict.updateValue(nameTextField.text !, forKey:sneakername)

let idPath = self.dbRef.child (users)。child(userID!)。child(sneakersPath)。childByAutoId()

//搜索将在这个文件路径上运行
let searchSnkPath = self.dbRef。 child(searchSnkPath)。childByAutoId()

idPath.updateChildValues(dict){
(err,ref)in
searchSnkPath.updateChildValues(dict)
}


$ / code $ / pre
$ b $ FBDatabase 我要搜索的数据存储在 root / searchSnkPath / autoID 中的路径,它有2个表示数据的名称为 sneakercondition sneakername 。我想从中获取搜索结果的路径是 root / searchSnkPath

  root 
|
@ -users
| |
| @ -userID
| |
| @ -sneakersPath
| |
| @ -autoID
| | -sneakercondition
| | -sneakername
@searchSnkPath
|
@ -autoID
| -sneakercondition
| -sneakername

如果我想搜索 searchSnkPath 并在这两个键上查询,那么在 config .js 文件我会找到 exports.paths ,里面有我要设置信息的地方搜索

  exports.paths = [
{
路径:https://sneakersearch-az12.firebaseio.com/searchSnkPath,/ / exp在步骤4中
index:firebase,//在步骤17中的exp
类型:sneakers,//在步骤19中的exp
fields:['sneakercondition','sneakername '] //这些是搜索的特定键(步骤4中的exp)
}
]

步骤4涵盖了所有这些
$ b

重要运行 git clone https:// github.com/firebase/flashlight (步骤2A)你需要将 cd 放入手电筒文件夹(步骤2B),从这一点开始的所有步骤都发生在手电筒文件夹和不是主要Xcode项目文件夹内。 在Xcode项目文件夹中没有任何东西不能工作,因为它没有package.json文件

第1部分 - Github步骤: p>


1•通过Heroku安装并运行ElasticSearch或添加盆景服务

1.comments:



- Bonsai 第10步

- 您需要按照以下顺序执行步骤1A-1E,然后才能继续操作

1.directions:


$ b 1A。下载并安装 Node.js from
https://nodejs.org/en/download/



1B。下载并安装 Heroku Toolbelt (它已被重命名为 Heroku CLI )在 https://devcenter.heroku.com/articles/hero KU-CLI 。 FYI我使用了OS X安装程序,而不是OS X Homebrew。


$ b 1C。在您下载并安装 Heroku Toolbelt / CLI 登录到Heroku.com并创建一个帐户



1D 创建一个 Heroku 帐户无需创建新的 Heroku应用程序您将在步骤9中使用命令行执行此操作。打开终端并运行: node -v 来找到它,这是非常简单的



1E。从当前节点版本运行(例如,您得到 v6.9.1 )。在步骤2D中,您必须确保其中的版本匹配此输出。


2•git clone https://github.com/firebase/flashlight


2.注释:
$ b - 假设Xcode项目位于名为的文件夹内的桌面上, sneakerSearchFolder



- 在终端里面 cd 到sneakerSearchFolder文件夹 - 即运行: code> cd Desktop / sneakerSearchFolder



- 在sneakerSearchFolder里面 clone github repo at https://github.com/ firebase / flashlight



- 重要然后 cd 手电筒文件夹即运行: cd手电筒



节点版本按照 https://devcenter.heroku.com/articles/部署nodejs



-run: node -v 得到节点版本手电筒文件夹(即 v6.9.1 )后面运行你做一个 Heroku实例你需要根据上面的 devcenter.heroku 链接



- 如果您刚刚运行了节点版本,那么在手电筒文件夹内与步骤1E中的版本不匹配,则需要更新手电筒文件夹内的版本以使其匹配。 将Node.js升级到最新版本 如果两个版本匹配,那么你不必担心这一点



- 假设您的节点版本匹配,打开 package.json 手电筒文件夹中添加文件,并添加一个engines c>节点版本您目前正在使用

 engines:{
node :node_version_num_you_got_back_from_running_node -v
}

2.directions:在终端中导航到你的Xcode项目所在的文件夹


$ b

2B。运行: git clone https://github.com/firebase/flashlight



。运行: cd手电筒



2D。 运行: node -v

打开手电筒文件夹,然后打开 package.json ,然后打开<$ c

code>。将下列内容添加到文件中。

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b)

2E-example。仅供参考。打开 package.json ,并在dependencies之后 右大括号,在那里添加。在大括号后面必须加上一个逗号。并且不要在版本号之前添加v。保存文件。

 dependencies:{
JQDeferred:〜1.9.1,
colors:〜0.6.2,
elasticsearch:^ 11.0.1,
firebase:^ 3.5.2
},
engines:{
node:6.9.1
}




3•npm install

从这一点来说,在您的手电筒文件夹中,而不是您的主项目的文件夹中的一切工作,否则你会得到错误



3.注释:



- 您应该仍然在您的手电筒 / p>

<登录到 Firebase ,在FB项目的控制台中,转到项目设置(在概述旁边的小圆形图标),在项目设置中选择 SERVICE ACCOUNTS ,请转到 Firebase Admin SDK 部分。有两件事你必须在这里做。 1.查找并复制您的 Firebase服务帐户,它看起来像 firebase-admin-81772@sneakersearch-az12.iam.gserviceaccount.com 和2 。在页面底部,你将不得不点击生成新的私钥按钮,它会下载一个未知文件你需要重命名为 service-account.json 。如果它将文件命名为 Unknown 之外的其他文件,只需将其重命名为 service-account.json 即可。将文件重命名后,将其拖到手电筒文件夹中,因为步骤4B FB_SERVICEACCOUNT 需要从那里访问该文件。请确保您将文件放入手电筒文件夹中



- 这不在github步骤中列出,但这是必要的。您必须将 Firebase Server SDK凭证添加到您的项目中



- 您将需要位于手电筒文件夹来运行$ npm install firebase-admin --save 命令,否则会出错,因为它会查找 packae.json 文件。该文件已经存在于你的手电筒文件夹中,而不是在你的主Xcode项目文件夹里面。

一个href =https://firebase.google.com/docs/server/setup =nofollow noreferrer> https://firebase.google.com/docs/server/setup , code>初始化SDK 部分。您需要从 Unknown 文件(现在应该重命名为 service-account.json )中的2个值初始化它。值在第5行 - private_key 和6 - clientEmail 。仅供参考 clientEmail Firebase服务帐户是相同的事情

<在这里 SDK



  var admin = require(firebase-admin); //输入刚安装的npm firebase-admin模块

admin.initializeApp({
credential:admin.credential.cert({
projectId:< PROJECT_ID> ,// projectId:是您的GoogleService-Info.plist文件中的PROJECT_ID
clientEmail:foo @< PROJECT_ID> .iam.gserviceaccount.com,//客户端电子邮件:位于未知文件的第6行这也是您的Firebase服务帐户info
privateKey:----- BEGIN PRIVATE KEY ----- \\\
< KEY> \\\
----- END PRIVATE KEY --- --\\\
// privateKey:不是你的API_KEY / FB_TOKEN,在第五行的未知文件里有一个非常长的多行private_key键,看起来像----- BEGIN PRIVATE KEY-- --- \\\
CYchgacopuyvpc017tEpcl889ljbsiugr4ygrphvuygpuy ... mutli-lines ... \\\
----- END PRIVATE KEY ----- \\\
。您需要从那里复制并粘贴到这里。包括----- BEGIN PRIVATE KEY ----- \\\
和\\\
----- END PRIVATE KEY ----- \\\

}),
databaseURL:https://< DATABASE_NAME> .firebaseio.com// databaseURL:是GoogleService-Info.plist文件中的DATABASE_URL
});

-FYI 初始化SDK 部分你也可以选择使用 path / to / serviceAccountKey.json 的顶部,而你可以提供重命名的未知文件的路径。我选择底部 inline 部分,因为它更容易。如果您按照以下步骤操作,则不必担心这一点。



- 位于手电筒文件夹内是一个 app.js 文件,复制并粘贴上面的代码,并将其放在文件的顶部。



在命令行终端内运行: npm install



- 如果一切顺利,唯一的警告是应该有没有存储库字段没有许可证字段



3.directions:



3A 。确保您的手电筒内的文件夹运行: pwd



Firebase控制台的服务帐户页面,然后单击生成新的私钥按钮下载一个未知文件。



3C。 Unknown 文件重命名为 service-account.json ,并将文件在手电筒内文件夹



3D。 -account.json 文件复制名为 client_email ,或者您可以复制服务帐户您的 Firebase服务帐户页面上的信息


$ b 3E。终端内运行: npm install firebase-admin --save



3F。复制初始化SDK 并用这些值初始化这些字段:

  v ar admin = require(firebase-admin); 

admin.initializeApp({
credential:admin.credential.cert({
projectId:sneakersearch-az12,// use your PROJECT_ID
clientEmail: firebase-admin-81772@sneakersearch-az12.iam.gserviceaccount.com,//客户端电子邮件:未知文件中的第6行
privateKey:----- BEGIN PRIVATE KEY ----- \\ \\ nCYchgacopuyvpc017tEpcl889ljbsiugr4ygrphvuygpuy ... mutli-lines ... \\\
----- END PRIVATE KEY ----- \\\
// privateKey:在未知文件
}的第5行)
databaseURL:https://sneakersearch-az12.firebaseio.com//使用你的DATABASE_URL
});

3G。里面手电筒文件夹,打开 app.js 文件,使用正确的值粘贴/保存上面的代码


$ b $运行: npm install


至少要设置FB_URL和
FB_SERVICEACCOUNT)



<在您的手电筒文件夹中,有一个文件夹

命名为 config.example.js ,打开它

- 在这个 config.example中。 js 文件是你找到 FB_URL FB_SERVICEACCOUNT 变量的地方13和23)

- 您需要更改 exports.FB_URL = process.env.FB_URL || 'https://< YOUR APP> .firebaseio.com'; exports.FB_URL = process.env.FB_URL || 'whatever_your_DATABASE_URL_is'; (请务必在单引号或双引号内放置 whatever_your_DATABASE_URL_is

- 在第23行 exports.FB_SERVICEACCOUNT = process.env.FB_ACC || 'service-account.json'; 是用于从步骤3C访问 service-account.json文件的东西(不需要添加或更改任何东西,因为它会自己访问它)



- 您现在必须设置数据所在的路径(如 searchPath 用于向上面的ViewController中的FB发送数据),索引(步骤17)以及要在64,65行和66行上监视的类型(类似于您的数据模型)

  exports.paths = [
{
path:users,// line 64
index: firebase,// line 65
type:user// line 66
},



$ code>。这是您要从哪里拉取搜索结果的地方,即< DATABASE_URL> / searchSnkPath



- index exp在步骤17中



- type exp in

-FYI第69-79行将设置另一个您想要监视的路径。如果需要,您可以删除或注释这些。你也可以创建更多的路径来监视,即如果你有一个路径< DATABASE_URL> / searchClothingPath ,那么你也可以设置搜索。你也可以添加更多的路径,如果你想:即

  exports.paths = [
{
路径:https://sneakersearch-az12.firebaseio.com/searchSnkPath
索引:firebase,
类型:运动鞋
},
{
路径:< DATABASE_URL> / searchClothingPath
index:firebase,
type:clothingDataModel,
fields:['jeans','shirts'] //完全可选使用

{
路径:< DATABASE_URL> / searchHatsPath
index:firebase,
类型:hatDataModel,

$等等...

-FYI 字段是将在ES中编入索引的。这是一个可选的东西来添加。如果你有10 ,只希望其中的2个是索引,那么你可以添加这个。只有那些2 才能被搜索。您也可以使用 config.js 文件中的解析函数来做同样的事情。

- 之后保存/关闭 config.example.js ,并将其重命名为 config.js


$ b

4.directions:
$ b
打开 config.example.js 文件并在第13行更改 exports.FB_URL = process.env.FB_URL || 'https://< YOUR APP> .firebaseio.com'; exports.FB_URL = process.env.FB_URL || 'https://sneakersearch-az12.firebaseio.com';



第23行是什么用于访问 service-account.json 文件(只要在步骤3C中重命名了 Unknown file

4C。第64,65,66行是我要监视的,在第67行,我添加了字段键为两个 Firebase数据库键尽管没有必要搜索,但仍需要搜索

  exports.paths = [
{
路径:https://sneakersearch-az12.firebaseio.com/searchSnkPath \",//line 64
index:firebase,// line 65
type:sneakers,// line 66
fields:['sneakercondition','sneakername'] //第67行
$,

4D。保存/关闭 config.example.js 文件。现在重命名文件 config.js
$ b


5•node app.js运行应用程序)

5.comments:



- 你将不会运行这个命令,直到最后,所以现在跳过它,但有一些你应该知道的。运行 node app.js 在您的本地机器上运行您的Heroku应用程序。它会在本地寻找你没有的ElasticSearch,所以你会得到连接错误。如果你想在本地运行,那么你必须在步骤12B运行 export BONSAI_URL =< your_bonsai_url>代码 - 可选,这是解决本地连接错误。如果您的应用程序在睡眠/崩溃(exp接近结束)时,您将不得不再次运行 export BONSAI_URL =< your_bonsai_url>命令。除此之外,Heroku会自动运行应用程序。



- 至此,您需要打开 app.js 文件并根据 https://docs.bonsai.io/ docs / nodejs 添加一些代码。您应该在 var elasticsearch = require('elasticsearch')声明之后的任何位置添加代码。

  / * 
这段代码已经在app.js文件中。你应该添加下面的代码

var elasticsearch = require('elasticsearch'),
conf = require('./ config'),
fbutil = require(' ./lib/fbutil'),
PathMonitor = require('./ lib / PathMonitor'),
SearchQueue = require('./ lib / SearchQueue');
* /

//您需要添加
var bonsai_url = process.env.BONSAI_URL;
var client = new elasticsearch.Client({
host:bonsai_url,
log:'trace'
});
//测试连接...
client.ping({
requestTimeout:30000,
hello:elasticsearch
},
function错误){
if(error){
console.error('>>>>>>'+ bonsai_url)
console.error('> ;&b; Elasticsearch cluster is down!');
} else {
console.log('All is well');
}
}
) ;

- 方向也表示运行$ export BONSAI_URL =https:/ /username:password@my-awesome-cluster-123.us-east-1.bonsai.io<换句话说 export BONSAI_URL =< your_BONSAI_URL>)这就是你要做什么,只要你想在本地运行你的应用程序使用ES。这并不意味着远程



5.directions:

5 。打开 app.js 文件并添加下面的代码并保存文件:

  var bonsai_url = process.env.BONSAI_URL; 
var client = new elasticsearch.Client({
host:bonsai_url,
log:'trace'
});
//测试连接...
client.ping({
requestTimeout:30000,
hello:elasticsearch
},
function错误){
if(error){
console.error('>>>>>>'+ bonsai_url)
console.error('> ;&b; Elasticsearch cluster is down!');
} else {
console.log('All is well');
}
}
) ;




6•curl -X POST http:// localhost:9200 / firebase

- 跳过这一步,因为在这一点上,你没有一个本地的 ES

code> on your cpu to index



6.directions:



6. SKIP THIS STEP


7•cd flashlight




7.comments:



-No need to run this, you should still be inside your flashlight folder



7.directions:



7. SKIP THIS STEP


8•heroku login

$ b$b

8.comments:



-Open terminal



-You will have to enter your Heroku’s email address and password. As you enter the password it will show up blank



8.directions:



8A. run: heroku login



8B. At the prompt enter your email address and password to login into Heroku


9•heroku create (add heroku to project)


9.comments:



-This is why you didn’t need to create a heroku app at step 1D. Now you will create and name your heroku app



-After you type in create you need to type in whatever name you want your heroku app’s name to be. i.e. I choose the name sneakersearchinstanceAtoZ



-After you run this command if you login into Heroku and you should see the app’s name listed. Go to the right corner, click the 9 dots, choose Dashboard



9.directions:



9. run: heroku create sneakersearchinstanceAtoZ


10•heroku addons:add bonsai (install bonsai)


10.comments:



-You will need to add a credit card to your Heroku account before you run this step otherwise after you run it it will say you have to do it. It’s still a free plan though. I’m not sure if you can add a Bonsai add on without a card



-To add a credit card go all the way to the right side, click the circular icon, choose Account Settings, then choose Billing



-You now need to add bonsai to your heroku app. You do this by running heroku addons:add bonsai --app <your-app-name>



-<your-app-name> is whatever the heroku app’s name you created in step 9



-after you create a bonsai cluster it will then want you to open up the cluster by running heroku addons:open bonsai



10.directions:



10A. log on to Heroku and add a credit card to the Billing Page



10B. run: heroku addons:add bonsai --app sneakersearchinstanceAtoZ//same exact name from step 9



10C. run heroku addons:open bonsai


11•heroku config (check bonsai instance info and copy your new
BONSAI_URL you will need it later)


11.comments:


$ b$b

-Running heroku config will get all your environment variables and their corresponding values. When you see your bonsai’s url, copy it’s value, you’ll need it for steps 12B and 17



-This is the exact same url you will see from step 10C



-The bonsai url might look something like https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net



11.directions:



11A. run: heroku config



11B. Copy the bonsai url that is returned


12•heroku config:set FB_NAME= FB_TOKEN=\"\" (declare
environment variables)


12.comments:



-12A is REQUIRED. You need to use your project’s GoogleService-Info.plist’s PROJECT_ID which is the FB_NAME and the API_KEY which is the FB_TOKEN for this step



-12B is optional. If you want to connect to ElasticSearch locally run this. You will have to set your bonsai url so that running node app.js won’t throw connection errors. You do this by running: export BONSAI_URL=\"<your_bonsai_url>\". You will need to run this command per terminal session or if your Heroku app falls asleep/crashes.



-Do not use spaces before or after the equal sign



12.directions:



12A(REQUIRED). run: heroku config:set FB_NAME=sneakersearch-az12 FB_TOKEN=0012abc789xyz00019



12B(Optional).run: export BONSAI_URL=\"https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net\"


13•git add config.js (update)


13.comments:



-If you run this you might get an error that says:
The following paths are ignored by one of your .gitignore files:
config.js
Use -f if you really want to add them.



-It’s saying to run git add config.js then add -f at the end



13.di rections:



13A. run: git add config.js



13B. If there is an error run: git add config.js -f


14•git commit -m \"configure bonsai\"


14.directions:



14. run: git commit -m \"configure bonsai\"


15•git push heroku master (deploy to heroku)


15.directions:



15. run: git push heroku master


16•heroku ps:scale worker=1 (start dyno worker)


16.comments:



-the answer to what this command does is here Can someone explain & quot;heroku ps:scale web=1"



16.directions:



16. run: heroku ps:scale worker=1


17•curl -X POST /firebase (ex:
https://username:password@yourbonsai.bonsai.io/firebase)


17.comments:



-Before you begin this step read @DoesData updated answer (below mines) to use curl -X PUT instead



-Grab the bonsai url you copied from step 11B



-Paste the url after the curl -X POST command and make sure you add /firebase to the end of it



-what this does is it creates an index named /firebase that points to your bonsai url. Open your config.js file and look for exports.paths (line 62). That has a key/value pair named index: \"firebase\"(line 65) , the value is pointing to the index you just created and accesses the ES cluster from there



-Basically in your config.js file, on line 65 the index value firebase has to exactly match the name /firebase that your adding to the end curl -X POST command. If the names don’t match then none of this will work.



-if successful you should get this response back: {\"acknowledged\":true}



17.directions:



17. run: curl -X POST https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net/firebase


18•Now time to use Step 5 node app.js (run the app)


18.comments:



-running this command will start the app locally. You can also run npm start but either way it will launch it on your local machine and you will need to run the code in Step 12B(Optional) for this to work



18.directions



18. run: node app.js


19• set your mappings object(s)


FYI Step 19 is very important. You MUST set your MAPPINGS OBJECT and it’s KEYS. I don’t have enough chars left to explain it in detail here. This is what Step 4’s type key uses to get set by. Watch this video to explain how to set your mappings object: https://www.youtube.com/watch?v=h3i3pqwjtjA&feature=youtu.be



19.directions:



19A. --open TextEdit or Sublime then create a file and name it sneakerfile.json. Save it and drag the file into your flashlight folder. You need the .json extension.



19B. -Inside that file add the following code, save and close the file:

{ 
\"sneakers\": {
\"properties\": {
\"sneakercondition\": {
\"type\": \"string\"
},
\"sneakername\": {
\"type\": \"string\"
}
}
}
}
//notice this is just like the Swift Sneakers Data Model declared at the beginning

19C. grab your BONSAI_URL run heroku config:get BONSAI_URL. My BONSAI_URL is https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net



19D. run: curl -XPOST https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net/firebase/sneakers/_mapping -d@sneakerfile.json



19E. run: curl -XGET <BONASI_URL>/firebase/sneakers/_mapping?pretty



Done with Part 1. Part 2 will explain Step 19 in detail



Further Info-



Heroku commands:



To check on your dyno



run: heroku ps



If you get the following then refer to the links below

=== web (Free): npm start (1) 
web.1: crashed 2017/01/01 12:00:00 -0500 (~ 38m ago)

=== worker (Free): node ./app.js (1)
worker.1: crashed 2017/01/01 12:00:00 -0500 (~ 10m ago)

After creating your Heroku app your dyno is under the Heroku Free Plan. It will eventually fall asleep/crash if it’s not being used within a certain time frame. To stop sleeping/crashing follow



Easy way to prevent Heroku idling?



https://devcenter.heroku.com/articles/free-dyno-hours



https://devcenter.heroku.com/articles/dyno-sleeping



Other commands:

heroku help //help 
heroku status //Heroku platform status
heroku logs //displays 100 logs
heroku logs --tail //realtime logs
heroku logs --tail | grep worker //dyno worker logs
heroku ps -a <heroku app name> //how many dyno hrs you have left
heroku config:get BONSAI_URL //gets only your bonsai url
heroku config //all your environment variables
heroku apps:info //your Heroku credentials

To get back to the command prompt press Ctrl+C



You can also contact Heroku Support or Bonsai Support as they are very helpful



I will post Part 2 very soon.


I'm building an iOS app in Swift with a Firebase backend. I need advanced search options for my app. I've been told I should use Flashlight/ElasticSearch via this github link https://github.com/firebase/flashlight

Assume my app's name is SneakerSearch and my

Firebase Project_ID is- sneakersearch-az12 
Firebase Web_API_Key is- abc123XYZ000...
Firebase App_Url is- gs://sneakersearch-az12.appspot.com

I need some advice with the steps for setting this up as I'm new to Heroku and Node.js. I never learned either before but I've already installed the Heroku tool belt and 'sudo gem heroku install' is done.

I've listed the github directions/steps and the the step(s) I took for each direction. I need assistance with directions: 1,4,5,6,9,10,12, and 15.

1.Install and run ElasticSearch or add Bonsai service via Heroku

1. I make an account at Heroku.

1.-QUESTION: Do I need to create the name of my app and deploy it after I've setup my Heroku account or should I wait until step #9?

2.git clone https://github.com/firebase/flashlight

2.I clone the above into my iOS app's project folder

3.npm install

3.At the prompt I first I run "npm init" then I run "npm install"

4. edit config.js (see comments at the top, you must set FB_URL and FB_SERVICEACCOUNT at a minimum)

4A.-QUESTION: What is "FB_SERVICEACCOUNT"? I'm using Firebase 3 and I couldn't find anything on a service account in my console. Is this another Firebase account that I have to setup for my project using node.js in addition to the Firebase swift project I've already made?

4B.-QUESTION: Where do I "edit config.js" and set my FB_URL and FB_SERVICEACCOUNT at? Should this be in my package.json file?

5.node app.js (run the app)

5.-QUESTION: In terminal I ran "node app.js" and got "throw err;^". Why did I get this error?

6.curl -X POST http://localhost:9200/firebase

6.-QUESTION: What is this for?

7.cd flashlight

7.switched to the flashlight dir

8.heroku login

8.logged in to Heroku

9.heroku create (add heroku to project)

9A-QUESTION: When I first made my account at Heroku should I have created a new app with my app's name and deployed it using the git instructions it has listed? If I should not have done that at first will running "heroku create" manage that process for me?

9B-QUESTION: Do I just run "heroku create" or do I run "heroku create -app's name- here"?

10.heroku addons:add bonsai (install bonsai)

10.-QUESTION: Do I need to make an account at Bonasi.io and install it before this step or does this set up a bonsai account for me? I've never used bonsai before.

11.heroku config (check bonsai instance info and copy your new BONSAI_URL - you will need it later)

11.I guess this question would depend on step #10.

12.heroku config:set FB_NAME=<instance> FB_TOKEN="<token>" (declare environment variables)

12.-QUESTION: What is the Firebase TOKEN? Is this my Web_API_Key, App_URL, or Project_ID? I could not find anything specific to "token" inside my firebase console. I'm using Firebase 3.

13.git add config.js (update)
git commit -m "configure bonsai"

13. commit with message

14.git push heroku master (deploy to heroku)

14. push to master

15.heroku ps:scale worker=1 (start dyno worker)

15.-QUESTION: What is this for?

解决方案

This is a 2 part answer with the 1st part going over the Github directions and ending on Step 19. The 2nd part extends more info that couldn't fit into the 1st part and it will begin on step 19 in detail. I'll have to add it to another question and link it to this.

Here are the Github steps listed in order. FYI I kept the original steps in line with how the original Github author listed them but underneath I put a bunch of sub-steps with detailed explanations and directions under each one.

Assuming you already created a Firebase project and got your GoogleService-Info.plist file

Open your GoogleService-Info.plist file. The following variables from the Github directions correlate with GoogleService-Info.plist keys

-FB_NAME is the same thing as your PROJECT_ID
-FB_URL is the same thing as your DATABASE_URL
-FB_TOKEN is the same thing as your API_KEY

So 

-if your PROJECT_ID is "sneakersearch-az12" then your FB_NAME is "sneakersearch-az12"
-if your DATABASE_URL is "https://sneakersearch-az12.firebaseio.com" then your FB_URL is "https://sneakersearch-az12.firebaseio.com"
-if your API_KEY is "0012abc789xyz00019" then your FB_TOKEN is "0012abc789xyz00019"

//These are not inside your GoogleService-Info.plist but you will encounter them later
-FB_SERVICEACCOUNT pertains to downloading a json file from the your project's Firebase console. You will need to go to the page SERVICE ACCOUNTS it's exp in step 3B
-clientEmail is the same thing as your Firebase Service Account. You get this from either the Unknown file or on your SERVICE ACCOUNTS page via the FB Console and it's exp in step 3D and 3B
-privateKey is the same thing as private_key but this key is NOT your API_KEY, it is a key that is inside the Unknown file from the SERVICE ACCOUNTS page. It looks something like: "-----BEGIN PRIVATE KEY-----\nCYchgacopuyvpc017246t124087t6hpUTYVPUSVDPUCHVEpcl889ljbsiugr4ygrphvuygpuy...mutli-lines...\n-----END PRIVATE KEY-----\n". Also exp in step 3B

Underneath each Github step I have comments and then directions. Inside the directions where I use the below values you should instead use your project's values. So for the step examples I'll use these keys and values:

//GoogleService-Info.plist
PROJECT_ID---aka--FB_NAME:  sneakersearch-az12
DATABASE_URL-aka--FB_URL:   https://sneakersearch-az12.firebaseio.com
API_KEY------aka--FB_TOKEN: 0012abc789xyz00019
//FB Service Account info
Firebase service account--aka--clientEmail: firebase-admin-81772@sneakersearch-az12.iam.gserviceaccount.com //this is auto generated for you once you've created your firebase project
//Heroku and Bonsai info
Heroku Instance Name--aka--Heroku App Name: sneakersearchinstanceAtoZ
BONASI_URL --aka--Bonsai Cluster URL:  https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net

Swift Data Model: (this will match what you put in your mappings object in Step 19)

class Sneakers: NSObject{
    var sneakercondition: String?
    var sneakername: String?
 }

VC with file paths where I send data to Firebase and searchSnkPath is a separate file path where Bonsai will run it's searches on:

@IBOutlet weak var conditionTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!

var dbRef: FIRDatabaseReference!
let userID = FIRAuth.auth()?.currentUser?.uid

override func viewDidLoad() {
    super.viewDidLoad()
    self.dbRef = FIRDatabase.database().reference()
 }

@IBAction func postDataButton(){

    var dict = [String:AnyObject]()
    dict.updateValue(conditionTextField.text!, forKey: "sneakercondition")
    dict.updateValue(nameTextField.text!, forKey: "sneakername")

    let idPath = self.dbRef.child("users").child(userID!).child("sneakersPath").childByAutoId()

        //searches will run on this file path
    let searchSnkPath = self.dbRef.child("searchSnkPath").childByAutoId()

    idPath.updateChildValues(dict){
       (err, ref) in
       searchSnkPath.updateChildValues(dict)
    }
  }
}

Inside FBDatabase the path where my data to search is stored at root/searchSnkPath/autoID and it has 2 keys named sneakercondition and sneakername that represents the data. The path I want to pull my search results from is root/searchSnkPath

root
  |
  @-users
  |   |
  |   @-userID
  |      |
  |      @-sneakersPath
  |            |
  |            @-autoID
  |                |-sneakercondition
  |                |-sneakername
  @searchSnkPath
      |
      @-autoID
          |-sneakercondition
          |-sneakername

If I want to search on the searchSnkPath and query on those 2 keys then inside the config.js file I'd find exports.paths and inside there is where I would set the info to search on

exports.paths = [
   {          
      path : "https://sneakersearch-az12.firebaseio.com/searchSnkPath", //exp in Step 4
      index: "firebase", //exp in Step 17
      type : "sneakers", //exp in Step 19
      fields: ['sneakercondition', 'sneakername'] //these are the specific keys to search on (exp in Step 4)
    }
]

Step 4 covers all this

Important after you run git clone https://github.com/firebase/flashlight (step 2A) you need to cd into the flashlight folder (step 2B) as ALL the steps from that point on happen inside the flashlight folder and NOT your main Xcode project's folder. Nothing will not work inside your Xcode project's folder because it doesn't have a package.json file

Part 1 - Github steps:

1•Install and run ElasticSearch or add Bonsai service via Heroku

1.comments:

-Bonsai will get added at step 10

-You DO need to have the following steps 1A-1E in order before you proceed

1.directions:

1A. Download and install Node.js from https://nodejs.org/en/download/

1B. Download and install the Heroku Toolbelt (it's been renamed Heroku CLI) at https://devcenter.heroku.com/articles/heroku-cli. FYI I used the OS X Installer and not OS X Homebrew.

1C. After you've downloaded and installed the Heroku Toolbelt/CLI log on to Heroku.com and create an account

1D. After creating a Heroku account no need to create a new Heroku App You will do this in step 9 using the command line. It's very easy

1E. Open terminal and run: node -v to find out the current node version your running (for example you get v6.9.1). In step 2D you will have to make sure the version from there matches this output.

2•git clone https://github.com/firebase/flashlight

2.comments:

-Assume the Xcode project lives on the desktop inside a folder named sneakerSearchFolder

-Inside terminal you cd to the sneakerSearchFolder folder- i.e. run: cd Desktop/sneakerSearchFolder

-Once inside the sneakerSearchFolder you clone the github repo at https://github.com/firebase/flashlight

-Important You then cd to flashlight folder i.e. run: cd flashlight

-You will need the node version your running according to https://devcenter.heroku.com/articles/deploying-nodejs

-run: node -v to get what node version is running inside the flashlight folder (i.e v6.9.1) later on when you make a Heroku instance you will need this according to the devcenter.heroku link above

-Now that your inside the flashlight folder, if the node version you just ran doesn't match the version from step 1E, you will need to update the version inside the flashlight folder to make them match. Upgrading Node.js to latest version If both versions match then you don't have to worry about this

-Assuming your node versions match, Open the package.json file inside your flashlight folder and add an "engines" object with the key's value being the node version you are currently using

"engines": {
    "node": "node_version_num_you_got_back_from_running_node -v"
  }

2.directions:

2A. in terminal navigate to whatever folder your Xcode project is in

2B. run: git clone https://github.com/firebase/flashlight

2C. run: cd flashlight

2D. run: node -v

2E. Open the flashlight folder then open package.json. Add the following to the file.

"engines": {
    "node": "whatever_was_returned_from_Step_2D"
  }

2E-example. FYI here's an example. Open package.json and after the "dependencies" closing brace, add it there. BE SURE TO ADD a COMMA after the closing brace. And don't add the "v" before the version number. Save the file.

"dependencies": {
    "JQDeferred": "~1.9.1",
    "colors": "~0.6.2",
    "elasticsearch": "^11.0.1",
    "firebase": "^3.5.2"
  },
"engines": {
    "node": "6.9.1"
  }

3•npm install

From this point on it's very important that your inside your flashlight folder and not your main project's folder for everything to work otherwise you will get errors

3.comments:

-You should still be inside your flashlight folder

-Log into Firebase, inside the console of your FB project, go to the Project's Settings (little round icon next to Overview), inside Project Settings choose SERVICE ACCOUNTS, go to the section Firebase Admin SDK. There are 2 things you have to do here. 1. Find and copy your Firebase service account, it looks like firebase-admin-81772@sneakersearch-az12.iam.gserviceaccount.com and 2. at the bottom of the page you will have to click the Generate New Private Key button, it will download an Unknown file that you will need to rename to service-account.json. If it names the file something besides Unknown just rename that to service-account.json. After you rename the file drag it into your flashlight folder because Step 4B FB_SERVICEACCOUNT will need to access this file from there. MAKE SURE YOU PUT THE FILE INSIDE THE FLASHLIGHT FOLDER!

-This isn't listed in the github steps but it's necessary. You must add Firebase Server SDK Credentials to your project

-You will need to be inside your flashlight folder to run the $npm install firebase-admin --save command or you'll get errors because it will look for a packae.json file. The file is already inside your flashlight folder and not inside your main Xcode project's folder

-Follow the directions from https://firebase.google.com/docs/server/setup, inside the Initialize the SDK section. You will need 2 of the values from the Unknown file (which should now be renamed service-account.json) to initialize it. The values are on lines 5-private_key and 6-clientEmail. FYI the clientEmail and Firebase service account are the same thing

-Here's what you are initializing inside the SDK:

var admin = require("firebase-admin"); //this imports the npm firebase-admin module you just installed

admin.initializeApp({
      credential: admin.credential.cert({
        projectId: "<PROJECT_ID>", //projectId: is the PROJECT_ID from your GoogleService-Info.plist file
        clientEmail: "foo@<PROJECT_ID>.iam.gserviceaccount.com", //clientEmail: is on  line 6 in the Unknown file which is also your "Firebase service account" info
        privateKey: "-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n" //privateKey: is NOT your API_KEY/FB_TOKEN. Inside the Unknown file on line 5 there is a very long multiline "private_key" key. It looks something like "-----BEGIN PRIVATE KEY-----\nCYchgacopuyvpc017tEpcl889ljbsiugr4ygrphvuygpuy...mutli-lines...\n-----END PRIVATE KEY-----\n". You need to copy and paste it from there to here. Be sure to include the "-----BEGIN PRIVATE KEY-----\n and \n-----END PRIVATE KEY-----\n
      }),
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com" //databaseURL: is the DATABASE_URL from your GoogleService-Info.plist file
    });

-FYI inside the Initialize the SDK section you also have the option of using the top part where it says path/to/serviceAccountKey.json and you can instead supply the path to the renamed Unknown file. I choose the bottom inline part as it was easier. If your following these steps you don't need to worry about this though.

-Inside the flashlight folder there is an app.js file, copy and paste the above code and put it at the top of the file

-Back inside terminal on the command line run: npm install

-If everything is all good the only warnings you should have are No repository field and No license field

3.directions:

3A. Make sure your inside the flashlight folder run: pwd

3B. Log into your Firebase Console's SERVICE ACCOUNTS page and click the Generate New Private Key button to download an Unknown file.

3C. Rename the Unknown file to service-account.json and put the file inside your flashlight folder

3D. Inside the service-account.json file copy the key named client_email or you can copy the service account info on your Firebase SERVICE ACCOUNTS page

3E. Inside terminal run: npm install firebase-admin --save

3F. Copy what's inside the section Initialize the SDK and initialize the fields with these values:

var admin = require("firebase-admin");

admin.initializeApp({
  credential: admin.credential.cert({
    projectId: "sneakersearch-az12", //use your PROJECT_ID
    clientEmail: "firebase-admin-81772@sneakersearch-az12.iam.gserviceaccount.com", //clientEmail: is on  line 6 in the Unknown file
    privateKey: "-----BEGIN PRIVATE KEY-----\nCYchgacopuyvpc017tEpcl889ljbsiugr4ygrphvuygpuy...mutli-lines...\n-----END PRIVATE KEY-----\n" //privateKey: is on line 5 in the Unknown file
  }),
  databaseURL: "https://sneakersearch-az12.firebaseio.com" //use your DATABASE_URL
});

3G. Inside the flashlight folder, open the app.js file, paste/save the above code inside of it with the correct values

3H. run: npm install

4•edit config.js (see comments at the top, you must set FB_URL and FB_SERVICEACCOUNT at a minimum)

4.comments:

-Inside your flashlight folder there is a file named config.example.js, open it

-Inside this config.example.js file is where you find the FB_URL and FB_SERVICEACCOUNT variables (they are listed on lines 13 and 23)

-You need to change exports.FB_URL = process.env.FB_URL || 'https://<YOUR APP>.firebaseio.com'; to exports.FB_URL = process.env.FB_URL || 'whatever_your_DATABASE_URL_is'; (be sure to put whatever_your_DATABASE_URL_is inside single or double quotes)

-on line 23 exports.FB_SERVICEACCOUNT = process.env.FB_ACC || 'service-account.json'; is what is used to access the service-account.json file from step 3C (there is no need to add or change anything here as it will access it on it's own)

-You will now have to setup the path where your data sits at (like the searchPath used to send data to FB inside the ViewController above), the index (Step 17), and the type (similar to your data model) that you want to monitor on line 64,65, and 66

exports.paths = [
  {
    path : "users",//line 64
    index: "firebase",//line 65
    type : "user"//line 66
  },

-path is where your data sits at inside FB. It's where you want to pull search results from i.e. <DATABASE_URL>/searchSnkPath

-index exp in Step 17

-type exp in Step 19

-FYI lines 69-79 would set up another path that you would want to monitor. You can delete or comment these out if you want. You can also create more paths to monitor i.e. If you had a path <DATABASE_URL>/searchClothingPath then you would set up search on that also. You can also add more paths if you want to i.e:

exports.paths = [
    {
      path : "https://sneakersearch-az12.firebaseio.com/searchSnkPath"
      index: "firebase",
      type : "sneakers"
    },
    {
      path : "<DATABASE_URL>/searchClothingPath"
      index: "firebase",
      type : "clothingDataModel",
      fields: ['jeans','shirts']//completely optional to use
    },
    {
      path : "<DATABASE_URL>/searchHatsPath"
      index: "firebase",
      type : "hatDataModel",
    },
    //etc...

-FYI Fields are the keys that will be indexed in ES. This is an optional thing to add. If you had 10 keys and only wanted 2 of them to be indexed then you would add this. This means of the 10 keys only those 2 keys would be searchable. You can also use the parse function inside the config.js file to do the same thing

-Afterwards save/close the config.example.js and rename it config.js

4.directions:

4A. Open the config.example.js file and on line 13 change exports.FB_URL = process.env.FB_URL || 'https://<YOUR APP>.firebaseio.com'; to exports.FB_URL = process.env.FB_URL || 'https://sneakersearch-az12.firebaseio.com';

4B. Line 23 is what is used to access the service-account.json file (as long as you renamed the Unknown file in step 3C just move on)

4C. Line 64,65,66, are what I want to monitor and on line 67 I added the fields key for the two Firebase Database Keys I want to search on although it is not necessary

exports.paths = [
  {
    path : "https://sneakersearch-az12.firebaseio.com/searchSnkPath",//line 64
    index: "firebase",//line 65
    type : "sneakers",//line 66
    fields: ['sneakercondition', 'sneakername']//line 67
  },

4D. Save/close the config.example.js file. Now rename the file config.js.

5•node app.js (run the app)

5.comments:

-You won't run this command until the very end so skip it for now but there is something you should know. Running node app.js runs your Heroku app on your local machine. It will look for ElasticSearch locally which you don't have so you will get connection errors. If you want to run it locally then you will have to run the export BONSAI_URL="<your_bonsai_url>" code at Step 12B-Optional which is needed to resolve local connection errors. If your app falls asleep/crashes (exp near the end) you will have to run the export BONSAI_URL="<your_bonsai_url>" command again. Other then that Heroku will run the app automatically when you push code up to it.

-As of now for this step you need to open your app.js file and according to https://docs.bonsai.io/docs/nodejs add some code. You should add the code anywhere after the var elasticsearch = require('elasticsearch') declaration.

/*
this code is already inside the app.js file. You should add the code anywhere below it

var elasticsearch = require('elasticsearch'),
  conf = require('./config'),
  fbutil = require('./lib/fbutil'),
  PathMonitor = require('./lib/PathMonitor'),
  SearchQueue = require('./lib/SearchQueue');
*/

//You need to add
var bonsai_url = process.env.BONSAI_URL;
var client = new elasticsearch.Client({
                         host: bonsai_url,
                         log: 'trace' 
                     });
    // Test the connection...
client.ping({
    requestTimeout: 30000,
    hello: "elasticsearch"
  },
  function (error) {
    if (error) {
      console.error('>>>My Bonsai url is>>>' + bonsai_url)
      console.error('>>>Elasticsearch cluster is down!');
    } else {
      console.log('All is well');
    }
  }
);

-The directions also says to run $ export BONSAI_URL="https://username:password@my-awesome-cluster-123.us-east-1.bonsai.io" (in other words export BONSAI_URL="<your_BONSAI_URL>") which is what you would do ONLY if you want to run your app locally to use ES. It's not meant for remote

5.directions:

5. Open the app.js file and add the code below and save the file:

var bonsai_url = process.env.BONSAI_URL;
var client = new elasticsearch.Client({
                         host: bonsai_url,
                         log: 'trace' 
                     });
    // Test the connection...
client.ping({
    requestTimeout: 30000,
    hello: "elasticsearch"
  },
  function (error) {
    if (error) {
      console.error('>>>My Bonsai url is>>>' + bonsai_url)
      console.error('>>>Elasticsearch cluster is down!');
    } else {
      console.log('All is well');
    }
  }
);

6•curl -X POST http://localhost:9200/firebase

6.comments:

-Skip this step because at this point you don't have a local ES on your cpu to index

6.directions:

6. SKIP THIS STEP

7•cd flashlight

7.comments:

-No need to run this, you should still be inside your flashlight folder

7.directions:

7. SKIP THIS STEP

8•heroku login

8.comments:

-Open terminal

-You will have to enter your Heroku's email address and password. As you enter the password it will show up blank

8.directions:

8A. run: heroku login

8B. At the prompt enter your email address and password to login into Heroku

9•heroku create (add heroku to project)

9.comments:

-This is why you didn't need to create a heroku app at step 1D. Now you will create and name your heroku app

-After you type in create you need to type in whatever name you want your heroku app's name to be. i.e. I choose the name sneakersearchinstanceAtoZ

-After you run this command if you login into Heroku and you should see the app's name listed. Go to the right corner, click the 9 dots, choose Dashboard

9.directions:

9. run: heroku create sneakersearchinstanceAtoZ

10•heroku addons:add bonsai (install bonsai)

10.comments:

-You will need to add a credit card to your Heroku account before you run this step otherwise after you run it it will say you have to do it. It's still a free plan though. I'm not sure if you can add a Bonsai add on without a card

-To add a credit card go all the way to the right side, click the circular icon, choose Account Settings, then choose Billing

-You now need to add bonsai to your heroku app. You do this by running heroku addons:add bonsai --app <your-app-name>

-<your-app-name> is whatever the heroku app's name you created in step 9

-after you create a bonsai cluster it will then want you to open up the cluster by running heroku addons:open bonsai

10.directions:

10A. log on to Heroku and add a credit card to the Billing Page

10B. run: heroku addons:add bonsai --app sneakersearchinstanceAtoZ//same exact name from step 9

10C. run heroku addons:open bonsai

11•heroku config (check bonsai instance info and copy your new BONSAI_URL you will need it later)

11.comments:

-Running heroku config will get all your environment variables and their corresponding values. When you see your bonsai's url, copy it's value, you'll need it for steps 12B and 17

-This is the exact same url you will see from step 10C

-The bonsai url might look something like https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net

11.directions:

11A. run: heroku config

11B. Copy the bonsai url that is returned

12•heroku config:set FB_NAME= FB_TOKEN="" (declare environment variables)

12.comments:

-12A is REQUIRED. You need to use your project's GoogleService-Info.plist's PROJECT_ID which is the FB_NAME and the API_KEY which is the FB_TOKEN for this step

-12B is optional. If you want to connect to ElasticSearch locally run this. You will have to set your bonsai url so that running node app.js won't throw connection errors. You do this by running: export BONSAI_URL="<your_bonsai_url>". You will need to run this command per terminal session or if your Heroku app falls asleep/crashes.

-Do not use spaces before or after the equal sign

12.directions:

12A(REQUIRED). run: heroku config:set FB_NAME=sneakersearch-az12 FB_TOKEN=0012abc789xyz00019

12B(Optional).run: export BONSAI_URL="https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net"

13•git add config.js (update)

13.comments:

-If you run this you might get an error that says: The following paths are ignored by one of your .gitignore files: config.js Use -f if you really want to add them.

-It's saying to run git add config.js then add -f at the end

13.directions:

13A. run: git add config.js

13B. If there is an error run: git add config.js -f

14•git commit -m "configure bonsai"

14.directions:

14. run: git commit -m "configure bonsai"

15•git push heroku master (deploy to heroku)

15.directions:

15. run: git push heroku master

16•heroku ps:scale worker=1 (start dyno worker)

16.comments:

-the answer to what this command does is here Can someone explain "heroku ps:scale web=1"

16.directions:

16. run: heroku ps:scale worker=1

17•curl -X POST /firebase (ex: https://username:password@yourbonsai.bonsai.io/firebase)

17.comments:

-Before you begin this step read @DoesData updated answer (below mines) to use curl -X PUT instead

-Grab the bonsai url you copied from step 11B

-Paste the url after the curl -X POST command and make sure you add /firebase to the end of it

-what this does is it creates an index named /firebase that points to your bonsai url. Open your config.js file and look for exports.paths (line 62). That has a key/value pair named index: "firebase"(line 65) , the value is pointing to the index you just created and accesses the ES cluster from there

-Basically in your config.js file, on line 65 the index value firebase has to exactly match the name /firebase that your adding to the end curl -X POST command. If the names don't match then none of this will work.

-if successful you should get this response back: {"acknowledged":true}

17.directions:

17. run: curl -X POST https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net/firebase

18•Now time to use Step 5 node app.js (run the app)

18.comments:

-running this command will start the app locally. You can also run npm start but either way it will launch it on your local machine and you will need to run the code in Step 12B(Optional) for this to work

18.directions

18. run: node app.js

19• set your mappings object(s)

FYI Step 19 is very important. You MUST set your MAPPINGS OBJECT and it's KEYS. I don't have enough chars left to explain it in detail here. This is what Step 4's type key uses to get set by. Watch this video to explain how to set your mappings object: https://www.youtube.com/watch?v=h3i3pqwjtjA&feature=youtu.be

19.directions:

19A. --open TextEdit or Sublime then create a file and name it sneakerfile.json. Save it and drag the file into your flashlight folder. You need the .json extension.

19B. -Inside that file add the following code, save and close the file:

{
  "sneakers": {
     "properties": {
       "sneakercondition": {
         "type": "string"
       },
       "sneakername": {
         "type": "string"
       }
     }
  }
}
//notice this is just like the Swift Sneakers Data Model declared at the beginning

19C. grab your BONSAI_URL run heroku config:get BONSAI_URL. My BONSAI_URL is https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net

19D. run: curl -XPOST https://abc123a01:01abc12de45xyz34@xyz-012345.us-east-1.bonsaisearch.net/firebase/sneakers/_mapping -d@sneakerfile.json

19E. run: curl -XGET <BONASI_URL>/firebase/sneakers/_mapping?pretty

Done with Part 1. Part 2 will explain Step 19 in detail

Further Info-

Heroku commands:

To check on your dyno

run: heroku ps

If you get the following then refer to the links below

=== web (Free): npm start (1)
web.1: crashed 2017/01/01 12:00:00 -0500 (~ 38m ago)

=== worker (Free): node ./app.js (1)
worker.1: crashed 2017/01/01 12:00:00 -0500 (~ 10m ago)

After creating your Heroku app your dyno is under the Heroku Free Plan. It will eventually fall asleep/crash if it's not being used within a certain time frame. To stop sleeping/crashing follow

Easy way to prevent Heroku idling?

https://devcenter.heroku.com/articles/free-dyno-hours

https://devcenter.heroku.com/articles/dyno-sleeping

Other commands:

heroku help //help
heroku status //Heroku platform status
heroku logs //displays 100 logs
heroku logs --tail //realtime logs
heroku logs --tail | grep worker //dyno worker logs
heroku ps -a <heroku app name> //how many dyno hrs you have left
heroku config:get BONSAI_URL //gets only your bonsai url
heroku config //all your environment variables
heroku apps:info //your Heroku credentials 

To get back to the command prompt press Ctrl+C

You can also contact Heroku Support or Bonsai Support as they are very helpful

I will post Part 2 very soon.

这篇关于信同数范范范读范辛范范范范范范辛范辛范范辛范范辛辛辛信范辛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆