插入文档

POST /v1/databases/{databaseId}/collections/{collection}:insert · API key

请求:JSON Lines(JSONL),Content-Type: application/x-ndjson · 响应:JSONL

请求体为 JSON Lines:每行一个 JSON 对象。缺少的字段使用集合的默认值。

curl -X POST "https://inceptiondb.hola.cloud/v1/databases/$INCEPTIONDB_DATABASE/collections/customers:insert" \
  -H "Api-Key: $INCEPTIONDB_API_KEY" \
  -H "Api-Secret: $INCEPTIONDB_API_SECRET" \
  -H "Content-Type: application/x-ndjson" \
  --data-binary '{"id":"ada","name":"Ada Lovelace","plan":"pro","mrr":120}
{"id":"alan","name":"Alan Turing","plan":"free","mrr":0}'
POST /v1/databases/$INCEPTIONDB_DATABASE/collections/customers:insert HTTP/1.1
Host: inceptiondb.hola.cloud
Api-Key: $INCEPTIONDB_API_KEY
Api-Secret: $INCEPTIONDB_API_SECRET
Content-Type: application/x-ndjson

{"id":"ada","name":"Ada Lovelace","plan":"pro","mrr":120}
{"id":"alan","name":"Alan Turing","plan":"free","mrr":0}
// Go 1.21+, standard library only. Save as main.go and run: go run main.go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	body := "{\"id\":\"ada\",\"name\":\"Ada Lovelace\",\"plan\":\"pro\",\"mrr\":120}\n{\"id\":\"alan\",\"name\":\"Alan Turing\",\"plan\":\"free\",\"mrr\":0}"

	req, err := http.NewRequest("POST", "https://inceptiondb.hola.cloud/v1/databases/" + os.Getenv("INCEPTIONDB_DATABASE") + "/collections/customers:insert", strings.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Api-Key", os.Getenv("INCEPTIONDB_API_KEY"))
	req.Header.Set("Api-Secret", os.Getenv("INCEPTIONDB_API_SECRET"))
	req.Header.Set("Content-Type", "application/x-ndjson")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.Status)
	fmt.Println(string(responseBody))
}
<?php
// PHP 8+ with the curl extension. Save as example.php and run: php example.php

$body = '{"id":"ada","name":"Ada Lovelace","plan":"pro","mrr":120}\n{"id":"alan","name":"Alan Turing","plan":"free","mrr":0}';

$ch = curl_init();

curl_setopt_array($ch, [
    CURLOPT_URL => 'https://inceptiondb.hola.cloud/v1/databases/' . getenv('INCEPTIONDB_DATABASE') . '/collections/customers:insert',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_HTTPHEADER => [
        'Api-Key: ' . getenv('INCEPTIONDB_API_KEY'),
        'Api-Secret: ' . getenv('INCEPTIONDB_API_SECRET'),
        'Content-Type: application/x-ndjson',
    ],
]);

$response = curl_exec($ch);
if ($response === false) {
    throw new Exception(curl_error($ch));
}
echo curl_getinfo($ch, CURLINFO_RESPONSE_CODE), "\n", $response, "\n";
curl_close($ch);
# Python 3.8+. Install: pip install requests. Save as example.py and run: python example.py
import os
import requests

headers = {
    "Api-Key": os.environ["INCEPTIONDB_API_KEY"],
    "Api-Secret": os.environ["INCEPTIONDB_API_SECRET"],
    "Content-Type": "application/x-ndjson",
}

body = "{\"id\":\"ada\",\"name\":\"Ada Lovelace\",\"plan\":\"pro\",\"mrr\":120}\n{\"id\":\"alan\",\"name\":\"Alan Turing\",\"plan\":\"free\",\"mrr\":0}"

response = requests.request(
    "POST",
    "https://inceptiondb.hola.cloud/v1/databases/" + os.environ["INCEPTIONDB_DATABASE"] + "/collections/customers:insert",
    headers=headers,
    data=body
)

print(response.status_code)
print(response.text)
// Node.js 18+. Save as example.mjs and run: node example.mjs
const body = "{\"id\":\"ada\",\"name\":\"Ada Lovelace\",\"plan\":\"pro\",\"mrr\":120}\n{\"id\":\"alan\",\"name\":\"Alan Turing\",\"plan\":\"free\",\"mrr\":0}";

const response = await fetch("https://inceptiondb.hola.cloud/v1/databases/" + process.env.INCEPTIONDB_DATABASE + "/collections/customers:insert", {
  method: "POST",
  headers: {
    "Api-Key": process.env.INCEPTIONDB_API_KEY,
    "Api-Secret": process.env.INCEPTIONDB_API_SECRET,
    "Content-Type": "application/x-ndjson"
  },
  body
});

console.log(response.status);
console.log(await response.text());
// Java 17+, standard library only. Save as Main.java and run: java Main.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        var body = """
{"id":"ada","name":"Ada Lovelace","plan":"pro","mrr":120}
{"id":"alan","name":"Alan Turing","plan":"free","mrr":0}
""";

        var request = HttpRequest.newBuilder()
            .uri(URI.create("https://inceptiondb.hola.cloud/v1/databases/" + System.getenv("INCEPTIONDB_DATABASE") + "/collections/customers:insert"))
            .method("POST", HttpRequest.BodyPublishers.ofString(body))
            .header("Api-Key", System.getenv("INCEPTIONDB_API_KEY"))
            .header("Api-Secret", System.getenv("INCEPTIONDB_API_SECRET"))
            .header("Content-Type", "application/x-ndjson")
            .build();

        var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
}

响应 201 Created,以 JSON Lines 返回已保存的文档:

1{"id":"ada","name":"Ada Lovelace","plan":"pro","mrr":120}
2{"id":"alan","name":"Alan Turing","plan":"free","mrr":0}

文档按顺序保存。插入在第一个被拒绝的文档处停止;之前的文档仍会保存。

  • JSON 数组([{...},{...}])不是 JSON Lines:会以 400 拒绝。
  • 如果集合不存在,插入会创建它。
  • 除非集合在 id 上有 map 索引,否则 id 不保证唯一。
状态码 何时
400 某行不是 JSON 对象(例如请求体是 JSON 数组),或包含重复的字段名。
409 唯一索引中已存在该值。

评论

发表评论