使用更新 CBOR 資料格式進行索引

Solr 支援 CBOR 格式進行索引和查詢。它支援大多數流行的語言和平台。與 JSON 相比,它更快且更有效率。

Python 範例

將以下程式碼另存為 cbor_post.py

import json
import requests
import cbor2

# JSON data to send (list of dictionaries)
json_data = [
    {
        "id" : "1",
        "name_s": "John Doe",
        "age_i": 30,
        "city_s": "New York"
    },
    {
        "id": "2",
        "name_s": "Jane Smith",
        "age_i": 25,
        "city_s": "London"
    }
]
# If there is only a single doc you can use the following
# json_data =    {
#         "id" : "6",
#         "name_s": "John Doe",
#         "age_i": 30,
#         "city_s": "New York"
#     }


# Convert JSON data to CBOR
cbor_data = cbor2.dumps(json_data)

# Set the endpoint URL
# ensure that the collection 'coll1' is already created
url = "https://127.0.0.1:8983/solr/coll1/update/cbor?commit=true"

# Send a POST request with CBOR data
response = requests.post(url, data=cbor_data, headers={"Content-Type": "application/cbor"})

# Check the response status
if response.status_code == 200:
    print("POST request sent successfully!")
    print("Response Body:", response.text)
else:
    print("Unexpected response status:", response.status_code)

執行程式

  1. 安裝 Python

  2. 確保已安裝相依性

    pip install requests cbor2
  3. 執行程式

    python3 cbor_post.py
  4. 檢查輸出

    POST request sent successfully!
    Response Body: {
    "responseHeader":{
    "rf":1,
    "status":0,
    "QTime":70
    }
    }

Node.js 範例

將以下程式碼儲存到名為 script.js 的檔案中

const cbor = require('cbor');
const axios = require('axios');

async function main() {
// JSON data to send (list of JSON objects)
const jsonData = [
{
"id" : "1",
"name_s": "John Doe",
"age_i": 30,
"city_s": "New York"
},
{
"id": "2",
"name_s": "Jane Smith",
"age_i": 25,
"city_s": "London"
},
];

  // Convert JSON data to CBOR
  const cborData = cbor.encode(jsonData);

  // Set the endpoint URL
  const url = "https://127.0.0.1:8983/solr/coll1/update/cbor?commit=true"

  try {
    // Send a POST request with CBOR data
    const response = await axios.post(url, cborData, {
      headers: {
        'Content-Type': 'application/cbor',
      },
    });

    // Process the response
    console.log('POST request sent successfully!');
    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error sending POST request:', error.message);
  }
}

main();

執行程式

  1. 安裝 Node.js

  2. 確保已安裝相依性

    npm install cbor axios
  3. 執行腳本

    node script.js
  4. 檢查輸出

    POST request sent successfully!
    Response: { responseHeader: { rf: 1, status: 0, QTime: 187 } }