使用IBM Cloudant搜尋
IBM® Cloudant® for IBM Cloud® 搜尋功能允許以語言感知的自由文字、多欄位和簡單地理空間查詢,並由開放原始碼搜尋引擎 Apache Lucene 支援。
IBM Cloudant 搜尋使用 Apache Lucene 查詢語法,使用一個、多個或所有索引欄位建立彈性查詢。
IBM Cloudant 搜尋如何運作
搜尋索引定義以 JavaScript 函式儲存在_設計文件_中,該函式會針對資料庫中的每個文件執行。 此功能定義哪些屬性會被編入索引,哪些屬性會儲存在索引中但不可搜尋,以及在編入索引前如何預先處理每個文字屬性 (使用選定的搜尋「分析器」)。
IBM Cloudant 搜尋可作用於整個資料庫,或對於分割的資料庫,作用於單一分割區,其中 是設計文件中的。options.partitioned true
何時使用 IBM Cloudant 搜尋
IBM Cloudant 搜尋非常適合
- 語言感知的全文檢索、通配符檢索以及數字或文字欄位的簡單範圍查詢。
- 在一組索引欄位上彈性查詢。
- 簡單的地理空間查詢,例如尋找最近處或使用邊界框尋找。
- 對結果集中的個別欄位進行計數聚合 - 稱為「分面」。
何時不使用 IBM Cloudant 搜尋
避免 IBM Cloudant 搜尋
- 聚合 (分面以外)。 改用「視圖」。
建立搜尋索引
若要建立搜尋索引,您可以將JavaScript函數新增至資料庫中的設計文件。 索引在處理一個搜尋請求後或伺服器偵測到文件更新後建立。 index 函式接受以下參數:
- 欄位名稱 - 查詢索引時要使用的欄位的名稱。 如果將此參數設為
default,則如果查詢語法中沒有指定字段,則查詢該字段。 - 您想要索引的數據,例如
doc.address.country。 - (可選)第三個參數包含以下欄位:
boost、facet、index和store。 稍後將更詳細地描述這些欄位。
預設情況下,搜尋索引回應會傳回 25 行。 可以使用 limit 參數變更傳回的行數。 但是,搜尋結果集限制為 200 行。 每個回應都包含一個 bookmark 欄位。 您可以在以後的查詢中包含 bookmark 欄位的值以查看回應。
您可以使用下列方法之一查詢 API:URI、IBM Cloudant Dashboard、curl 或瀏覽器插件,例如 Postman 或 RESTClient。
請參閱以下定義搜尋索引的範例設計文件:
{
"_id": "_design/search_example",
"indexes": {
"animals": {
"index": "function(doc){ ... }"
}
}
}
搜尋索引分割區類型
搜尋索引會從 options.partitioned 包含該項目的設計文件中的欄位。
索引函數
如果您嘗試使用不存在的資料欄位建立索引,則會失敗。 若要避免此問題,請使用適當的 保護子句。
您的索引函數在記憶體受限的環境中運行,其中文件本身構成該環境中使用的記憶體的一部分。 您的程式碼的堆疊和文件必須適合該記憶體。 文件的最大大小限制為 64 MB。
在搜尋索引中,不要使用多種資料類型對相同欄位名稱建立索引。 如果在同一個搜尋索引函數中使用不同的資料類型對相同的欄位名稱建立索引,則可能會發生錯誤。 當您查詢包含 was indexed without position data 欄位的搜尋索引時,會發生此錯誤。 例如,請勿將這兩行包含在同一搜尋索引函數中。 這些行將 myfield 欄位索引為兩種不同的資料類型:字串 "this is a string" 和數字 123。
index("myfield", "this is a string");
index("myfield", 123);
索引欄位中包含的函數是一個JavaScript函數,為資料庫中的每個文件呼叫該函數。 此函數將文件作為參數,從中提取一些數據,然後呼叫 index 欄位中定義的函數來索引該數據。
index 函數採用三個參數,其中第三個參數是可選的。
第一個參數是查詢索引時要使用的欄位名稱,在後面查詢的 Lucene 語法部分中指定。 以下查詢中出現一個範例:
query=color:red
Lucene 欄位名稱 color 是 index 函數的第一個參數。
query 參數可以縮寫為 q,因此編寫查詢的另一種方式如下例所示。
q=color:red
如果在定義名稱時使用特殊值 "default",則不必在查詢時指定欄位名稱。 效果是可以簡化查詢:
query=red
第二個參數是要索引的資料。 為資料建立索引時,請記住以下資訊:
- 此資料只能是字串、數字或布林值。 其他類型從索引函數呼叫傳回錯誤。
- 如果您的函數在執行時傳回錯誤,則出於此原因或其他原因,該文件不會新增至該搜尋索引。
第三個可選參數是具有以下欄位的JavaScript物件:
| 選項 | 說明 | 值 | 預設值 |
|---|---|---|---|
boost |
指定搜尋結果中的相關性的數字。 使用大於 1 的提升值編製索引的內容比未使用提升值編製索引的內容更相關。 提升值小於 1 的內容就沒那麼相關。 | 正浮點數 | 1(無提升) |
facet |
建立多面索引。 有關更多信息,請參閱 分面。 | true |
false |
index |
資料是否已建立索引,如果是,如何建立索引。 如果設定為 false,則資料不能用於搜索,但如果 store 設定為 true,仍然可以從索引中檢索資料。 有關詳細信息,請參閱 分析器。 |
true, false |
true |
store |
如果 true,則在搜尋結果中傳回該值;否則,不傳回該值。 |
true, false |
false |
如果不設定 store 參數,則不會傳回文件的索引資料結果來回應查詢。
請參閱以下範例搜尋索引函數:
function(doc) {
index("default", doc._id);
if (doc.min_length) {
index("min_length", doc.min_length, {"store": true});
}
if (doc.diet) {
index("diet", doc.diet, {"store": true});
}
if (doc.latin_name) {
index("latin_name", doc.latin_name, {"store": true});
}
if (doc.class) {
index("class", doc.class, {"store": true});
}
}
儲存 vs include_docs=true
當 IBM Cloudant 從搜尋傳回資料時,您可以選擇下列選項:store: true 或 include_docs=true。 請參閱下列說明:
- 在索引時間,選擇
{store: true}選項。 此選項表示您要處理的欄位需要儲存在索引內。 即使欄位本身不被用於索引,也可以被「儲存」。 例如,您可能想要「儲存」一個電話號碼,即使您的搜尋演算法不包括以電話號碼搜尋。 - 在查詢時,傳入
?include_docs=true來指示 IBM Cloud,您希望傳回每個匹配文件的整個正文。
第一個選項意味著您需要較大的索引,但這是擷取資料最快的方式。 第二個選項可讓索引保持較小的規模,但會為 IBM Cloud 增加額外的查詢時間工作,因為它必須在計算出搜尋結果集後取得文件正文。 此程序的執行速度可能較慢,並會進一步加重 IBM Cloud 集群的負擔。
如果可能的話,請使用下列指引選擇第一個選項:
- 只索引您想要搜尋的欄位。
- 只儲存需要在查詢時擷取的欄位。
索引保護條款
index 函數需要將要索引的資料欄位的名稱作為第二個參數。 但是,如果文檔不存在該資料字段,則會發生錯誤。 解決方案是使用適當的「保護子句」來檢查該欄位是否存在。 在嘗試建立對應索引之前,此子句包含預期的資料類型。
請參閱以下範例定義,該定義沒有對索引資料欄位的類型進行任何驗證:
if (doc.min_length) {
index("min_length", doc.min_length, {"store": true});
}
您可以使用JavaScript typeof 運算子來實作保護子句測試。 如果該欄位存在並且具有預期的類型,則傳回正確的類型名稱。 保護子句測試成功,這意味著使用索引函數是安全的。 如果該欄位不存在,您將無法傳回預期的欄位類型,這就是您不會嘗試對該欄位建立索引的原因。
如果測試以下值之一,JavaScript會認為結果為 false:
- '不明確的'
- 空值
- 數字+0
- 數字-0
- NaN (非數字)
- 「」(空字串)
請參閱以下範例,該範例在嘗試建立索引之前使用保護子句檢查所需的資料欄位是否存在並儲存數字:
if (typeof doc.min_length === 'number') {
index("min_length", doc.min_length, {"store": true});
}
使用通用保護子句測試來確保候選資料欄位的類型已定義。
請參閱以下「通用」保護子句範例:
if (typeof doc.min_length) !== 'undefined') {
// The field exists, and does have a type, so we can proceed to index using it.
...
}
分析儀
分析器是定義如何識別文字中的術語的設定。 有關詳細信息,請參閱 搜尋分析器。
如果您需要對 多種語言建立索引,分析器會很有幫助。
下表顯示了IBM Cloudant搜尋支援的通用分析器清單:
| 分析器 | 說明 |
|---|---|
classic |
標準 Lucene 分析器,約版本3.1。 |
email |
與 standard 分析器類似,但更努力地將電子郵件地址作為完整標記進行配對。 |
keyword |
輸入根本沒有被標記化。 |
simple |
在非字母處劃分文本。 |
simple_asciifolding |
在非字母處劃分文本。 將字元轉換為最接近的 ASCII 對應值 |
standard |
預設分析器。 它實作了 Unicode™ 文字分段演算法的分詞規則。 |
whitespace |
在空白邊界處劃分文字。 |
請參閱以下範例分析器文件:
{
"_id": "_design/analyzer_example",
"indexes": {
"INDEX_NAME": {
"index": "function (doc) { ... }",
"analyzer": "$ANALYZER_NAME"
}
}
}
特定語言的分析器
這些分析器省略了特定語言中的常見單詞,許多分析器也 刪除了前綴和後綴。 語言的名稱也是分析器的名稱。
arabicarmenianbasquebulgarianbraziliancatalancjk(中文、日文、韓文)chinese(smartcn)czechdanishdutchenglishfinnishfrenchgermangreekgalicianhindihungarianindonesianirishitalianjapanese(kuromoji)latviannorwegianpersianpolish(stempel)portugueseromanianrussianspanishswedishthaiturkish
特定於語言的分析器針對指定的語言進行了最佳化。 您不能將通用分析器與特定於語言的分析器結合。 相反,您可以使用 perfield 分析器 為文件中的不同欄位選擇不同的分析器。
每場分析器
perfield 分析器針對不同的領域配置了許多分析器。
請參閱以下範例,該範例為不同欄位定義了不同的分析器:
{
"_id": "_design/analyzer_example",
"indexes": {
"INDEX_NAME": {
"analyzer": {
"name": "perfield",
"default": "english",
"fields": {
"spanish": "spanish",
"german": "german"
}
},
"index": "function (doc) { ... }"
}
}
}
停用詞
停用詞是沒有被索引的詞。 您可以透過將分析器字串轉換為物件來在設計文件中定義它們。
keyword、simple 和 whitespace 分析器不支援停用詞。
standard 分析器的預設停用詞包含在以下列表中:
"a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if",
"in", "into", "is", "it", "no", "not", "of", "on", "or", "such",
"that", "the", "their", "then", "there", "these", "they", "this",
"to", "was", "will", "with"
請參閱以下定義非索引(“停止”)詞的範例:
{
"_id": "_design/stop_words_example",
"indexes": {
"INDEX_NAME": {
"analyzer": {
"name": "portuguese",
"stopwords": [
"foo",
"bar",
"baz"
]
},
"index": "function (doc) { ... }"
}
}
}
測試分析器標記化
您可以透過將範例資料發佈到 _search_analyze 端點來測試分析器標記化的結果。
請參閱以下使用 HTTP 測試 keyword 分析器的範例:
Host: $ACCOUNT.cloudant.com
POST /_search_analyze HTTP/1.1
Content-Type: application/json
{"analyzer":"keyword", "text":"ablanks@renovations.com"}
請參閱以下使用命令列測試 keyword 分析器的範例:
curl "https://$ACCOUNT.cloudant.com/_search_analyze" \
-H "Content-Type: application/json" \
-d '{"analyzer":"keyword", "text":"ablanks@renovations.com"}'
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostSearchAnalyzeOptions;
import com.ibm.cloud.cloudant.v1.model.SearchAnalyzeResult;
Cloudant service = Cloudant.newInstance();
PostSearchAnalyzeOptions searchAnalyzerOptions =
new PostSearchAnalyzeOptions.Builder()
.analyzer("keyword")
.text("ablanks@renovations.com")
.build();
SearchAnalyzeResult response =
service.postSearchAnalyze(searchAnalyzerOptions).execute()
.getResult();
System.out.println(response);
import { CloudantV1 } from '@ibm-cloud/cloudant';
const service = CloudantV1.newInstance({});
service.postSearchAnalyze({
analyzer: 'keyword',
text: 'ablanks@renovations.com',
}).then(response => {
console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1
service = CloudantV1.new_instance()
response = service.post_search_analyze(
analyzer='keyword',
text='ablanks@renovations.com'
).get_result()
print(response)
postSearchAnalyzeOptions := service.NewPostSearchAnalyzeOptions(
"keyword",
"ablanks@renovations.com",
)
searchAnalyzeResult, _, err := service.PostSearchAnalyze(postSearchAnalyzeOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(searchAnalyzeResult, "", " ")
fmt.Println(string(b))
前面的 Go 範例需要以下導入區塊:
import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)
請參閱以下測試 keyword 分析器的結果:
{
"tokens": [
"ablanks@renovations.com"
]
}
請參閱以下使用 HTTP 測試 standard 分析器的範例:
Host: $ACCOUNT.cloudant.com
POST /_search_analyze HTTP/1.1
Content-Type: application/json
{"analyzer":"standard", "text":"ablanks@renovations.com"}
請參閱以下使用命令列測試 standard 分析器的範例:
curl "https://$ACCOUNT.cloudant.com/_search_analyze" -H "Content-Type: application/json"
-d '{"analyzer":"standard", "text":"ablanks@renovations.com"}'
查看 standard 分析器的測試結果如下:
{
"tokens": [
"ablanks",
"renovations.com"
]
}
查詢
建立搜尋索引後,您可以對其進行查詢。
-
使用以下請求執行分區查詢:
GET /$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_search/$INDEX_NAME -
使用以下請求運行全域查詢:
GET /$DATABASE/_design/$DDOC/_search/$INDEX_NAME
使用 query 參數指定您的搜尋。
請參閱以下使用 HTTP 查詢分割索引的範例:
GET /$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_search/$INDEX_NAME?include_docs=true&query="*:*"&limit=1 HTTP/1.1
Content-Type: application/json
Host: $ACCOUNT.cloudant.com
請參閱以下使用命令列查詢分區索引的範例:
curl "https://$ACCOUNT.cloudant.com/$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_search/$INDEX_NAME?include_docs=true&query=\"*:*\"&limit=1"
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostPartitionSearchOptions;
import com.ibm.cloud.cloudant.v1.model.SearchResult;
Cloudant service = Cloudant.newInstance();
PostPartitionSearchOptions searchOptions =
new PostPartitionSearchOptions.Builder()
.db("<db-name>")
.partitionKey("<partition-key>")
.ddoc("<ddoc>")
.index("<index-name>")
.query("*:*")
.includeDocs(true)
.limit(1)
.build();
SearchResult response =
service.postPartitionSearch(searchOptions).execute()
.getResult();
System.out.println(response);
import { CloudantV1 } from '@ibm-cloud/cloudant';
const service = CloudantV1.newInstance({});
service.postSearch({
db: '<db-name>',
partitionKey: '<partition-key>',
ddoc: '<ddoc>',
index: '<index-name>',
query: '*:*',
includeDocs: true,
limit: 1
}).then(response => {
console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1
service = CloudantV1.new_instance()
response = service.post_search(
db='<db-name>',
partition_key='<partition-key>',
ddoc='<ddoc>',
index='<index-name>',
query='*:*',
include_docs=True,
limit=1
).get_result()
print(response)
postPartitionSearchOptions := service.NewPostPartitionSearchOptions(
"<db-name>",
"<partition-key>",
"<ddoc>",
"<index-name>",
"*:*",
)
postPartitionSearchOptions.SetIncludeDocs(true)
postPartitionSearchOptions.SetLimit(1)
searchResult, _, err := service.PostPartitionSearch(postPartitionSearchOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(searchResult, "", " ")
fmt.Println(string(b))
前面的 Go 範例需要以下導入區塊:
import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)
請參閱以下使用 HTTP 查詢全局索引的範例:
GET /$DATABASE/_design/$DDOC/_search/$INDEX_NAME?include_docs=true&query="*:*"&limit=1 HTTP/1.1
Content-Type: application/json
Host: $ACCOUNT.cloudant.com
請參閱以下使用命令列查詢全域索引的範例:
curl "https://$ACCOUNT.cloudant.com/$DATABASE/_design/$DDOC/_search/$INDEX_NAME?include_docs=true&query=\"*:*\"&limit=1"
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostSearchOptions;
import com.ibm.cloud.cloudant.v1.model.SearchResult;
Cloudant service = Cloudant.newInstance();
PostSearchOptions searchOptions = new PostSearchOptions.Builder()
.db("<db-name>")
.ddoc("<ddoc>")
.index("<index-name>")
.query("*:*")
.includeDocs(true)
.limit(1)
.build();
SearchResult response =
service.postSearch(searchOptions).execute()
.getResult();
System.out.println(response);
import { CloudantV1 } from '@ibm-cloud/cloudant';
const service = CloudantV1.newInstance({});
service.postSearch({
db: '<db-name>',
ddoc: '<ddoc>',
index: '<index-name>',
query: '*:*',
includeDocs: true,
limit: 1
}).then(response => {
console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1
service = CloudantV1.new_instance()
response = service.post_search(
db='<db-name>',
ddoc='<ddoc>',
index='<index-name>',
query='*:*',
include_docs=True,
limit=1
).get_result()
print(response)
postSearchOptions := service.NewPostSearchOptions(
"<db-name>",
"<ddoc>",
"<index-name>",
"*:*",
)
postSearchOptions.SetIncludeDocs(true)
postSearchOptions.SetLimit(1)
searchResult, _, err := service.PostSearch(postSearchOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(searchResult, "", " ")
fmt.Println(string(b))
前面的 Go 範例需要以下導入區塊:
import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)
查詢參數
您必須先啟用 分面,然後才能使用下列參數:counts 和 drilldown。
| 引數 | 說明 | 選用 | 類型 | 支援的值 | 分區查詢 |
|---|---|---|---|---|---|
bookmark |
從先前的搜尋中收到的書籤。 此參數允許對結果進行分頁。 如果書籤後不存在任何結果,您將收到包含空行數組和相同書籤的回應,確認結果清單的末尾。 | yes |
字串 | 是 | |
counts |
此欄位定義了請求計數的字串欄位名稱陣列。 回應包括與搜尋查詢相符的文件中該欄位名稱的每個唯一值的計數。 必須啟用 分面 才能使此參數發揮作用。 | 是 | JSON | 字段名稱的 JSON 數組。 | 否 |
drilldown |
該字段可以多次使用。 每次使用都定義一對欄位名稱和值。 搜尋僅符合包含指定欄位中提供的值的文件。 它與在 q 參數中使用 "fieldname:value" 的不同之處僅在於不分析值。 必須啟用 分面 才能使此參數發揮作用。 |
否 | JSON | 一個 JSON 數組,包含兩個元素:欄位名稱和值。 | 是 |
group_field |
用於對搜尋匹配項進行分組的欄位。 | 是 | 字串 | 包含字串字段名稱的字串。 無法使用包含數字、物件或陣列等其他資料的欄位。 | 否 |
group_limit |
最大組數。 僅當指定 group_field 時才能使用此欄位。 |
是 | 數值 | 否 | |
group_sort |
此欄位定義使用 group_field 搜尋中群組的順序。 預設排序順序是相關性。 |
是 | JSON | 此欄位可以具有與排序欄位相同的值,因此支援單一欄位和欄位數組。 | 否 |
highlight_fields |
指定要反白的欄位。 如果指定,結果物件包括一個 highlights 字段,其中每個指定字段都有一個條目。 |
是 | 字串陣列 | 是 | |
highlight_pre_tag |
在反白輸出中插入到突出顯示的單字之前的字串。 | 是,預設為 <em> |
字串 | 是 | |
highlight_post_tag |
在反白輸出中插入到突出顯示的單字之後的字串。 | 是,預設為 </em> |
字串 | 是 | |
highlight_number |
在反白顯示中傳回的片段數。 如果搜尋項目超過片段大小,則傳回整個搜尋項目。 | 是,預設為 1 | 數值 | 是 | |
highlight_size |
將字段內容分割為多個字符,即所謂的片段,並僅突出顯示指定片段內的匹配項。 | 是,預設為 100 個字符 | 數值 | 是 | |
include_docs |
在回應中包含文件的完整內容。 | 是 | 布林 | 是 | |
include_fields |
要包含在搜尋結果中的欄位名稱的 JSON 陣列。 包含的任何欄位都必須使用 store:true 選項進行索引。 |
是的,預設是所有字段。 | 字串陣列 | 是 | |
limit |
將回傳的文件數量限制為指定數量。 對於分組搜索,此參數限制每組的文件數量。 | 是 | 數值 | 限制值可以是 200 以內的任意正整數。 | 是 |
q |
query 的縮寫。 執行 Lucene 查詢。 |
否 | 字串或數字 | 是 | |
query |
執行 Lucene 查詢。 | 否 | 字串或數字 | 是 | |
ranges |
此欄位定義多面數字搜尋欄位的範圍。 該值是一個 JSON 對象,其中字段名稱是分面數字搜尋字段,字段的值是 JSON 對象。 JSON 物件的欄位名稱是範圍的名稱。 這些值是描述範圍的字串,例如 "[0 TO 10]"。 |
是 | JSON | 該值必須是一個對象,其中的欄位以對像作為其值。 這些物件必須具有以範圍作為欄位值的字串。 | 否 |
sort |
指定結果的排序順序。 在分組搜尋中(使用 group_field 時),此參數指定組內的排序順序。 預設排序順序是相關性。 |
是 | JSON | "fieldname<type>" 或 -fieldname<type> 形式的 JSON 字串,表示降序排列。 fieldname 是字串或數字欄位的名稱,type 可以是數字、字串或 JSON 字串陣列。 type 部分是可選的,預設為 number。 一些例子是
"foo"、"-foo"、"bar<string>"、"-foo<number>" 和 ["-foo<number>","bar<string>"]。 用於排序的字串欄位不得為分析欄位。
用於排序的欄位必須由用於搜尋查詢的相同索引器編制索引。 |
是 |
stale |
不要等待索引完成建置才傳回結果。 | 是 | 字串 | OK | 是 |
不要組合 bookmark 和 stale 選項。 這些選項限制了用於回應的分片副本的選擇。 一起使用時,當您嘗試聯繫速度慢或不可用的副本時,這些選項可能會導致問題。
使用 include_docs=true 可能會對 效能產生影響。
相關性
當可能傳回多個結果時,可以對它們進行排序。 預設情況下,排序順序由“相關性”決定。
相關性是根據 Apache Lucene Scoring來衡量的。 例如,如果您在簡單的資料庫中搜尋單字 example,則兩個文件可能包含該單字。 如果一個文檔提及單字 example 10 次,但第二個文檔僅提及兩次,則第一個文檔被認為更「相關」。
如果您不提供 sort 參數,則預設使用相關性。 首先返回得分最高的比賽。
如果您提供 sort 參數,則按該順序傳回符合項,忽略相關性。
如果您想要使用 sort 參數,並在搜尋結果中包含按相關性排序,請在 sort 參數中使用特殊欄位 -<score> 或 <score>。
發布搜尋查詢
而不是使用 GET HTTP 方法、您也可以使用 POST。
POST 查詢的主要優點是它們可以有請求正文,因此您可以將請求指定為 JSON 物件。 上表中的每個參數都對應於請求正文中 JSON 物件中的一個欄位。
請參閱以下使用 HTTP 來 POST 搜尋請求的範例:
POST /db/_design/ddoc/_search/searchname HTTP/1.1
Content-Type: application/json
Host: $ACCOUNT.cloudant.com
請參閱以下使用命令列 POST 搜尋請求的範例:
curl "https://$ACCOUNT.cloudant.com/$DATABASE/_design/$DDOC/_search/$INDEX_NAME" -X POST -H "Content-Type: application/json" -d @search.json
請參閱以下包含搜尋請求的範例 JSON 文件:
{
"q": "index:my query",
"sort": "foo",
"limit": 3
}
分頁
查詢語法
IBM Cloudant搜尋查詢語法是基於 Lucene 語法。 搜尋查詢採用 name:value 的形式,除非省略名稱,在這種情況下,它們使用預設字段,如以下範例所示:
請參閱以下範例搜尋查詢表達式:
// Birds
class:bird
// Animals that begin with the letter "l"
l*
// Carnivorous birds
class:bird AND diet:carnivore
// Herbivores that start with letter "l"
l* AND diet:herbivore
// Medium-sized herbivores
min_length:[1 TO 3] AND diet:herbivore
// Herbivores that are 2m long or less
diet:herbivore AND min_length:[-Infinity TO 2]
// Mammals that are at least 1.5m long
class:mammal AND min_length:[1.5 TO Infinity]
// Find "Meles meles"
latin_name:"Meles meles"
// Mammals who are herbivore or carnivore
diet:(herbivore OR omnivore) AND class:mammal
// Return all results
*:*
多個欄位的查詢可以邏輯組合,群組和欄位可以進一步分組。 可用的邏輯運算子會區分大小寫,包括 AND、+、OR、NOT 以及 - 範圍查詢可以對字串或數字運行。
如果您想要模糊搜索,可以運行帶有 ~ 的查詢來查找類似搜索詞的詞。 例如,
look~ 查找術語 book 和 took。
如果範圍查詢的上限都是僅包含數字的字串,則邊界將被視為數字而不是字串。 例如,如果您使用查詢 mod_date:["20170101" TO "20171231"] 進行搜索,則結果包括 mod_date 位於數值 20170101 和 20171231 之間的文檔,而不是字串「20170101」和「20171231」之間的文檔。
您可以透過添加 ^ 和正數來更改搜尋詞的重要性。 此變更會建立包含或多或少相關的術語的匹配項,與提升值的冪成比例。 預設值為1,表示匹配強度不增加或減少。 小數值 0 - 1 會降低重要性,使配對強度變弱。 大於 1 的值會增加重要性,使匹配強度更強。
支援通配符搜索,單一 ( ? ) 和多個 ( * ) 字元搜尋。 例如,
dat? 將匹配 date 和 data, 而 dat* 將匹配 date、data、database, 以及 dates。 通配符必須位於搜尋字詞之後。
使用 *:* 傳回所有結果。
搜尋結果集限制為 200 行,預設傳回 25 行。 可以使用 limit 參數 變更傳回的行數。
如果搜尋查詢未指定 "group_field" 參數,則回應將包含書籤。 如果此書籤之後作為 URL 參數提供、回應會跳過已經看到的行、這樣就可以快速輕鬆地獲得下一組結果。
如果搜尋查詢中包含 "group_field" 參數, 則回應永遠不會包含書籤。
group_field、group_limit 和 group_sort 選項僅在進行全域查詢時可用。
如果要搜尋以下字符,則需要對其進行轉義:
+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /
若要轉義這些字元之一,請使用前面的反斜線字元 ( \ )。
對搜尋查詢的回應包括每個結果的 order 欄位。
order 欄位是數組,其中第一個元素是 sort 參數中指定的一個或多個欄位。 如果查詢中不包含 sort 參數,則 order 欄位包含 Lucene 相關性分數。
如果您使用 地理搜尋 中所述的 sort by distance 功能,則第一個元素是距離某個點的距離。 距離用公里或英里來測量。
訂單數組中的第二個元素可以忽略。 此功能僅供故障排除之用。
刻面
IBM Cloudant搜尋還支援分面搜索,從而可以快速輕鬆地發現有關匹配項的聚合資訊。 您可以使用特殊的 ?q=*:* 查詢語法來匹配所有文檔,並使用返回的方面來優化您的查詢。 若要指示某個欄位必須為分面查詢建立索引,請在其選項中設定 {"facet": true}。
請參閱以下範例搜尋查詢,指定啟用分面搜尋:
function(doc) {
index("type", doc.type, {"facet": true});
index("price", doc.price, {"facet": true});
}
若要使用構面,索引中的所有文件必須包含啟用構面的所有欄位。 如果您的文件不包含所有字段,您會收到 bad_request 錯誤,原因如下:「field_name 不存在」。 如果每個文件不包含構面的所有字段,請為每個字段建立單獨的索引。 如果未為每個欄位建立單獨的索引,則必須僅包含包含所有欄位的文件。 使用單一 if 語句驗證每個文件中是否存在欄位。
請參閱以下範例 if 語句來驗證每個文件中是否存在必填欄位:
if (typeof doc.town == "string" && typeof doc.name == "string") {
index("town", doc.town, {facet: true});
index("name", doc.name, {facet: true});
}
個數
counts 選項僅在進行全域查詢時可用。
counts 構面語法採用欄位列表,並傳回每個命名欄位的每個唯一值的查詢結果數。
只有當索引值是字串時,count 操作才有效。 索引值不能是混合型別。 例如,如果索引了 100 個字串和一個數字,則該索引不能用於 count 操作。 您可以使用 typeof 運算子檢查類型, 並使用 parseInt、 parseFloat`` 或 .toString() 函式進行轉換。
請參閱以下使用 counts 構面語法的範例查詢:
?q=*:*&counts=["type"]
使用 counts 構面語法後,請參閱以下範例回應:
{
"total_rows":100000,
"bookmark":"g...",
"rows":[...],
"counts":{
"type":{
"sofa": 10,
"chair": 100,
"lamp": 97
}
}
}
drilldown
drilldown 選項僅在進行全域查詢時可用。
您可以將結果限制為尺寸等於指定標籤的文件。 透過向搜尋查詢新增 drilldown=["dimension","label"] 來限制結果。 您可以包含多個 drilldown 參數來限制多個維度的結果。
使用 drilldown 參數與在 q 參數中使用 key:value 類似,但 drilldown 參數傳回分析器可能會跳過的值。
例如,如果分析器沒有物件 "a" 這樣的停用詞建立索引,則 drilldown 參數會在您指定 drilldown=["key","a"] 時傳回它。
範圍
ranges 選項僅在進行全域查詢時可用。
range 分面語法重複使用範圍的標準 Lucene 語法來傳回適合每個指定類別的結果計數。 包含範圍查詢以方括號 ( [, ] ) 表示。 獨佔範圍查詢以大括號 ( {, } ) 表示。
索引值不能是混合型別。 例如,如果索引了 100 個字串和一個數字,則該索引不能用於 range 操作。 您可以使用 typeof 運算子檢查類型, 並使用 parseInt、 parseFloat`` 或 .toString() 函式進行轉換。
請參閱以下使用分面搜尋來符合 ranges 的請求範例:
?q=*:*&ranges={"price":{"cheap":"[0 TO 100]","expensive":"{100 TO Infinity}"}}
對分面搜尋進行 ranges 檢查後,請參閱以下範例結果:
{
"total_rows":100000,
"bookmark":"g...",
"rows":[...],
"ranges": {
"price": {
"expensive": 278682,
"cheap": 257023
}
}
}
地理搜尋
除了按文字欄位的內容進行搜尋之外,您還可以按與地理座標的距離對結果進行排序。
要以這種方式對結果進行排序,您必須為表示經度和緯度的兩個數字欄位建立索引。
然後,您可以使用特殊的 <distance...> 排序欄位進行查詢,該欄位需要五個參數:
- 經度欄位名稱 - 經度欄位的名稱(範例中為
mylon)。 - 緯度欄位名稱 - 緯度欄位的名稱(範例為
mylat)。 - 原點經度 - 您要依距離排序的地點的經度。
- 原點緯度 - 您要按距離排序的地點的緯度。
- 單位 - 使用的單位包括:
km代表公里或mi代表英里。 距離在訂單字段中返回。
您可以將按距離排序與任何其他搜尋查詢結合起來,例如緯度和經度的範圍搜尋或涉及非地理資訊的查詢。
這樣,您就可以在邊界框中進行搜索,並使用額外的條件縮小搜索範圍。
請參閱以下地理資料範例:
{
"name":"Aberdeen, Scotland",
"lat":57.15,
"lon":-2.15,
"type":"city"
}
請參閱以下包含地理資料搜尋索引的設計文件範例:
function(doc) {
if (doc.type && doc.type == 'city') {
index('city', doc.name, {'store': true});
index('lat', doc.lat, {'store': true});
index('lon', doc.lon, {'store': true});
}
}
請參閱以下範例,該範例使用 HTTP 進行查詢,依據北半球城市到紐約的距離排序:
GET /examples/_design/cities-designdoc/_search/cities?q=lat:[0+TO+90]&sort="<distance,lon,lat,-74.0059,40.7127,km>" HTTP/1.1
Host: $ACCOUNT.cloudant.com
請參閱以下範例,該範例使用命令列進行查詢,按北半球城市到紐約的距離對城市進行排序:
curl "https://$ACCOUNT.cloudant.com/examples/_design/cities-designdoc/_search/cities?q=lat:\[0+TO+90\]&sort=\"<distance,lon,lat,-74.0059,40.7127,km>\""
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostSearchOptions;
import com.ibm.cloud.cloudant.v1.model.SearchResult;
import java.util.Arrays;
Cloudant service = Cloudant.newInstance();
PostSearchOptions searchOptions = new PostSearchOptions.Builder()
.db("examples")
.ddoc("cities-designdoc")
.index("cities")
.query("lat:\\[0+TO+90\\]")
.sort(Arrays.asList("<distance,lon,lat,-74.0059,40.7127,km>"))
.build();
SearchResult response =
service.postSearch(searchOptions).execute()
.getResult();
System.out.println(response);
import { CloudantV1 } from '@ibm-cloud/cloudant';
const service = CloudantV1.newInstance({});
service.postSearch({
db: 'examples',
ddoc: 'cities-designdoc',
index: 'cities',
query: 'lat:\\[0+TO+90\\]',
sort: ['<distance,lon,lat,-74.0059,40.7127,km>']
}).then(response => {
console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1
service = CloudantV1.new_instance()
response = service.post_search(
db='examples',
ddoc='cities-designdoc',
index='cities',
query='lat:\\[0+TO+90\\]',
sort=['<distance,lon,lat,-74.0059,40.7127,km>']
).get_result()
print(response)
postSearchOptions := service.NewPostSearchOptions(
"examples",
"cities-designdoc",
"cities",
"lat:\\[0+TO+90\\]",
)
postSearchOptions.SetSort([]string{"<distance,lon,lat,-74.0059,40.7127,km>"})
searchResult, _, err := service.PostSearch(postSearchOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(searchResult, "", " ")
fmt.Println(string(b))
前面的 Go 範例需要以下導入區塊:
import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)
請參閱以下範例(縮寫)回應,其中包含按距離紐約的距離排序的北半球城市清單:
{
"total_rows": 205,
"bookmark": "g1A...XIU",
"rows": [
{
"id": "city180",
"order": [
8.530665755719783,
18
],
"fields": {
"city": "New York, N.Y.",
"lat": 40.78333333333333,
"lon": -73.96666666666667
}
},
{
"id": "city177",
"order": [
13.756343205985946,
17
],
"fields": {
"city": "Newark, N.J.",
"lat": 40.733333333333334,
"lon": -74.16666666666667
}
},
{
"id": "city178",
"order": [
113.53603438866077,
26
],
"fields": {
"city": "New Haven, Conn.",
"lat": 41.31666666666667,
"lon": -72.91666666666667
}
}
]
}
突出顯示搜尋詞
有時,取得提及搜尋字詞的上下文很有用,以便您可以向使用者顯示更強調的結果。
若要獲得更強調的結果,請將 highlight_fields 參數新增至搜尋查詢。 指定您想要摘錄的欄位名稱,並傳回反白的搜尋字詞。
預設情況下,搜尋字詞放置在 <em> 標籤中以突出顯示它,但可以使用 highlights_pre_tag 和 highlights_post_tag 參數覆蓋突出顯示。
分片長度預設為100個字元。 可以使用 highlights_size 參數請求不同的長度。
highlights_number 參數控制傳回的片段數量,預設為 1。
在回應中,新增一個 highlights 字段,每個字段名稱都有一個子字段。
對於每個字段,您都會收到一組片段,其中突出顯示了搜尋字詞。
為了突出顯示工作,請使用 store: true 選項將欄位儲存在索引中。
請參閱以下使用 HTTP 在啟用高亮顯示的情況下進行搜尋的範例:
GET /movies/_design/searches/_search/movies?q=movie_name:Azazel&highlight_fields=["movie_name"]&highlight_pre_tag=" "&highlight_post_tag=" "&highlights_size=30&highlights_number=2 HTTP/1.1
HOST: $ACCOUNT.cloudant.com
Authorization: ...
請參閱以下範例,其中啟用了突出顯示的命令列搜尋:
curl "https://$ACCOUNT.cloudant.com/movies/_design/searches/_search/movies?q=\"movie_name:Azazel\"&highlight_fields=\[\"movie_name\"\]&highlight_pre_tag=\" \"&highlight_post_tag=\" \"&highlights_size=30&highlights_number=2" \
-X GET
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostSearchOptions;
import com.ibm.cloud.cloudant.v1.model.SearchResult;
import java.util.Arrays;
Cloudant service = Cloudant.newInstance();
PostSearchOptions searchOptions = new PostSearchOptions.Builder()
.db("movies")
.ddoc("searches")
.index("movies")
.query("movie_name:Azazel")
.highlightFields(Arrays.asList("[\"movie_name\"]"))
.highlightPreTag("\" \"")
.highlightPostTag("\" \"")
.highlightSize(30)
.highlightNumber(2)
.build();
SearchResult response =
service.postSearch(searchOptions).execute()
.getResult();
System.out.println(response);
import { CloudantV1 } from '@ibm-cloud/cloudant';
const service = CloudantV1.newInstance({});
service.postSearch({
db: 'movies',
ddoc: 'searches',
index: 'movies',
query: 'movie_name:Azazel',
highlightFields: ['["movie_name"]'],
highlightPreTag: '" "',
highlightPostTag: '" "',
highlightSize: 30,
highlightNumber: 2
}).then(response => {
console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1
service = CloudantV1.new_instance()
response = service.post_search(
db='movies',
ddoc='searches',
index='movies',
query='movie_name:Azazel',
highlight_fields=['["movie_name"]'],
highlight_pre_tag='" "',
highlight_post_tag='" "',
highlight_size=30,
highlight_number=2
).get_result()
print(response)
postSearchOptions := service.NewPostSearchOptions(
"movies",
"searches",
"movies",
"movie_name:Azazel",
)
postSearchOptions.SetHighlightFields([]string{"[\"movie_name\"]"})
postSearchOptions.SetHighlightPreTag("\" \"")
postSearchOptions.SetHighlightPostTag("\" \"")
postSearchOptions.SetHighlightSize(30)
postSearchOptions.SetHighlightNumber(2)
searchResult, _, err := service.PostSearch(postSearchOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(searchResult, "", " ")
fmt.Println(string(b))
前面的 Go 範例需要以下導入區塊:
import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)
請參閱以下反白的搜尋結果範例:
{
"highlights": {
"movie_name": [
" on the Azazel Orient Express",
" Azazel manuals, you"
]
}
}
搜尋索引元數據
若要檢索有關搜尋索引的信息,您可以向 _search_info 傳送 GET 請求,如以下範例所示。
DDOC 指包含索引的設計文檔,INDEX_NAME 是索引的名稱。
請參閱以下使用 HTTP 來請求搜尋索引元資料的範例:
GET /$DATABASE/_design/$DDOC/_search_info/$INDEX_NAME HTTP/1.1
請參閱以下使用命令列請求搜尋索引元資料的範例:
curl "https://$ACCOUNT.cloudant.com/$DATABASE/_design/$DDOC/_search_info/$INDEX_NAME" \
-X GET
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.GetSearchInfoOptions;
import com.ibm.cloud.cloudant.v1.model.SearchInfoResult;
Cloudant service = Cloudant.newInstance();
GetSearchInfoOptions infoOptions =
new GetSearchInfoOptions.Builder()
.db("<db-name>")
.ddoc("<ddoc>")
.index("<index-name>")
.build();
SearchInfoResult response =
service.getSearchInfo(infoOptions).execute()
.getResult();
System.out.println(response);
import { CloudantV1 } from '@ibm-cloud/cloudant';
const service = CloudantV1.newInstance({});
service.getSearchInfo({
db: '<db-name>',
ddoc: '<ddoc>',
index: '<index-name>'
}).then(response => {
console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1
service = CloudantV1.new_instance()
response = service.get_search_info(
db='<db-name>',
ddoc='<ddoc>',
index='<index-name>'
).get_result()
print(response)
getSearchInfoOptions := service.NewGetSearchInfoOptions(
"<db-name>",
"<ddoc>",
"<index-name>",
)
searchInfoResult, _, err := service.GetSearchInfo(getSearchInfoOptions)
if err != nil {
panic(err)
}
b, _ := json.MarshalIndent(searchInfoResult, "", " ")
fmt.Println(string(b))
前面的 Go 範例需要以下導入區塊:
import (
"encoding/json"
"fmt"
"github.com/IBM/cloudant-go-sdk/cloudantv1"
)
回應包括有關索引的信息,例如索引中的文件數和磁碟上索引的大小。
請求搜尋索引元資料後,請參閱以下回應範例:
{
"name": "_design/DDOC/INDEX",
"search_index": {
"pending_seq": 7125496,
"doc_del_count": 129180,
"doc_count": 1066173,
"disk_size": 728305827,
"committed_seq": 7125496
}
}