[Mark Logic] CRUD + α par "Java Client API"

introduction

J'ai écrit le code pour CRUD les données (JSON) sur MarkLogic en utilisant le "Java Client API".

environnement

CRUD

C'est un CRUD de base.

Créer un document

Créez un nouveau document. Laissez MarkLogic gérer la génération de l'URI du document.

create


public class CreateApp {

	public static void main(String[] args) {
		CreateApp app = new CreateApp();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();
		Transaction tran = client.openTransaction();

		try {
			String json = ""
					+ "{"
					+ "    \"aaa\" : \"AAA\","
					+ "    \"bbb\" : \"BBB\","
					+ "    \"ccc\" : 111,"
					+ "    \"ddd\" : ["
					+ "        {"
					+ "            \"ddd-1\" : \"DDD-1\","
					+ "            \"ddd-2\" : 11"
					+ "        },"
					+ "        {"
					+ "            \"ddd-1\" : \"DDD-2\","
					+ "            \"ddd-2\" : 22"
					+ "        }"
					+ "    ]"
					+ "}";

			create(client, json, tran);
			tran.commit();

		} catch (Exception ex) {
			tran.rollback();
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private String create(DatabaseClient client, String jsonData, Transaction tran) {
		JSONDocumentManager docMgr = client.newJSONDocumentManager();
		//Spécifiez l'extension
		DocumentUriTemplate uriTemplate = docMgr.newDocumentUriTemplate("json");
		//Spécifiez le répertoire
		uriTemplate.setDirectory("/xxx/yyy/");

		DocumentDescriptor desc = docMgr.create(uriTemplate, new StringHandle(jsonData), tran);
		//Renvoyer l'URI du document à l'appelant
		return desc.getUri();
	}

	private DatabaseClient createDatabaseClient() {
		DatabaseClient client =
				DatabaseClientFactory.newClient(
						"xxx", 111, "xxx",
						new DigestAuthContext("xxx", "xxx"));
		return client;
	}
}

Recherche et lecture de documents

Une recherche QBE identifie l'URI et charge le document.

read


public class ReadApp {

	public static void main(String[] args) {
		ReadApp app = new ReadApp();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();

		try {
			String query = ""
					+ "{"
					+ "    \"$query\" : {"
					+ "        \"aaa\" : \"AAA\","
					+ "        \"bbb\" : \"BBB\","
					+ "        \"$filtered\" : false"
					+ "    }"
					+ "}";

			List<String> jsonList = search(client, "/xxx/yyy/", query, null);
			if (jsonList.isEmpty()) {
				return;
			}

			String uri = jsonList.get(0);
			String json = read(client, uri, null);
			System.out.println("____ uri  :" + uri);
			System.out.println("____ json :" + json);

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private List<String> search(DatabaseClient client, String dir, String query, Transaction tran) {

		QueryManager queryMgr = client.newQueryManager();
		queryMgr.setPageLength(100); //Par défaut 10

		StringHandle strHandle = new StringHandle(query).withFormat(Format.JSON);
		RawQueryByExampleDefinition querydef = queryMgr.newRawQueryByExampleDefinition(strHandle);
		querydef.setDirectory(dir);

		SearchHandle searchHandle = queryMgr.search(querydef, new SearchHandle(), 1, tran, null);

		List<String> uriList = new ArrayList<String>();
		MatchDocumentSummary[] results = searchHandle.getMatchResults();
		for (MatchDocumentSummary summary : results) {
			uriList.add(summary.getUri());
		}

		return uriList;
	}

	private String read(DatabaseClient client, String uri, Transaction tran) {
		JSONDocumentManager docMgr = client.newJSONDocumentManager();
		String jsonData = docMgr.read(uri, new StringHandle(), tran).get();
		return jsonData;
	}

	private DatabaseClient createDatabaseClient() {
		//réduction
	}
}

Recherche et mise à jour de documents (mise à jour)

La recherche QBE identifie l'URI et met à jour (écrase) le document.

update


public class UpdateApp {

	public static void main(String[] args) {
		UpdateApp app = new UpdateApp();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();
		Transaction tran = client.openTransaction();

		try {
			String query = ""
					+ "{"
					+ "    \"$query\" : {"
					+ "        \"aaa\" : \"AAA\","
					+ "        \"bbb\" : \"BBB\","
					+ "        \"$filtered\" : false"
					+ "    }"
					+ "}";

			String json = ""
					+ "{"
					+ "    \"aaa\" : \"AAAAAA\","
					+ "    \"bbb\" : \"BBBBBB\","
					+ "    \"ccc\" : 111111,"
					+ "    \"ddd\" : ["
					+ "        {"
					+ "            \"ddd-1\" : \"DDDDDD-1\","
					+ "            \"ddd-2\" : 1111"
					+ "        },"
					+ "        {"
					+ "            \"ddd-1\" : \"DDDDDD-2\","
					+ "            \"ddd-2\" : 2222"
					+ "        }"
					+ "    ]"
					+ "}";

			List<String> jsonList = search(client, "/xxx/yyy/", query, null);
			if (jsonList.isEmpty()) {
				return;
			}

			String uri = jsonList.get(0);
			update(client, uri, json, tran);
			tran.commit();

		} catch (Exception ex) {
			tran.rollback();
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private List<String> search(DatabaseClient client, String dir, String query, Transaction tran) {
		//réduction
	}

	private void update(DatabaseClient client, String uri, String jsonData, Transaction tran) {
		JSONDocumentManager docMgr = client.newJSONDocumentManager();
		StringHandle strHandle = new StringHandle().with(jsonData);
		docMgr.write(uri, strHandle, tran);
	}

	private DatabaseClient createDatabaseClient() {
		//réduction
	}
}

Recherche et suppression de documents

Une recherche QBE identifie l'URI et supprime le document.

delete


public class DeleteApp {

	public static void main(String[] args) {
		DeleteApp app = new DeleteApp();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();
		Transaction tran = client.openTransaction();

		try {
			String query = ""
					+ "{"
					+ "    \"$query\" : {"
					+ "        \"aaa\" : \"AAA\","
					+ "        \"bbb\" : \"BBB\","
					+ "        \"$filtered\" : false"
					+ "    }"
					+ "}";

			List<String> jsonList = search(client, "/xxx/yyy/", query, null);
			if (jsonList.isEmpty()) {
				return;
			}

			String uri = jsonList.get(0);
			delete(client, uri, tran);
			tran.commit();

		} catch (Exception ex) {
			tran.rollback();
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private List<String> search(DatabaseClient client, String dir, String query, Transaction tran) {
		//réduction
	}

	private void delete(DatabaseClient client, String uri, Transaction tran) {
		JSONDocumentManager docMgr = client.newJSONDocumentManager();
		docMgr.delete(uri, tran);
	}

	private DatabaseClient createDatabaseClient() {
		//réduction
	}
}

Ne mettez à jour qu'une partie du document.

Mise à jour partielle du document (mise à jour de la valeur)

Spécifiez le chemin dans le document pour mettre à jour la valeur.

Mise à jour de la valeur


public class PatchApp1 {

	public static void main(String[] args) {
		PatchApp1 app = new PatchApp1();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();
		Transaction tran = client.openTransaction();

		try {
			String uri = "/xxx/yyy/zzz.json";
			patch(client, uri, "$.bbb", "XXXXXX", tran);
			tran.commit();

		} catch (Exception ex) {
			tran.rollback();
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private void patch(DatabaseClient client, String uri, String path, String value, Transaction tran) {

		JSONDocumentManager jsonMgr = client.newJSONDocumentManager();

		DocumentPatchBuilder patchBuilder = jsonMgr.newPatchBuilder().pathLanguage(PathLanguage.JSONPATH);
		patchBuilder.replaceValue(path, value);
		PatchHandle patchHandle = patchBuilder.build();

		jsonMgr.patch(uri, patchHandle, tran);
	}

	private DatabaseClient createDatabaseClient() {
		//réduction
	}
}

Mise à jour partielle du document (ajouté à l'élément du tableau)

Ajoutez un élément à la fin de l'élément du tableau.

Ajouter à l'élément du tableau


public class PatchApp2 {

	public static void main(String[] args) {
		PatchApp2 app = new PatchApp2();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();
		Transaction tran = client.openTransaction();

		try {
			String uri = "/xxx/yyy/zzz.json";
			String fragment = ""
					+ "{"
					+ "    \"ddd-1\" : \"DDD-3\","
					+ "    \"ddd-2\" : 33"
					+ "}";
			patch(client, uri, "$.[\"ddd\"]", fragment, tran);
			tran.commit();

		} catch (Exception ex) {
			tran.rollback();
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private void patch(DatabaseClient client, String uri, String fragmentPath, String fragmentData, Transaction tran) {

		JSONDocumentManager jsonMgr = client.newJSONDocumentManager();

		DocumentPatchBuilder patchBuilder = jsonMgr.newPatchBuilder().pathLanguage(PathLanguage.JSONPATH);
		patchBuilder.insertFragment(fragmentPath, Position.LAST_CHILD, fragmentData);
		PatchHandle patchHandle = patchBuilder.build();

		jsonMgr.patch(uri, patchHandle, tran);
	}

	private DatabaseClient createDatabaseClient() {
		//réduction
	}
}

Mise à jour partielle du document (remplacer les éléments du tableau)

Remplace complètement le contenu des éléments du tableau.

Remplacer les éléments du tableau


public class PatchApp3 {

	public static void main(String[] args) {
		PatchApp3 app = new PatchApp3();
		app.execute(args);
	}

	private void execute(String[] args) {

		DatabaseClient client = createDatabaseClient();
		Transaction tran = client.openTransaction();

		try {
			String uri = "/xxx/yyy/zzz.json";
			String fragment = ""
					+ "[{"
					+ "    \"ddd-1\" : \"DDD-1\","
					+ "    \"ddd-2\" : 11"
					+ "}]";
			patch(client, uri, "$.[\"ddd\"]", fragment, tran);
			tran.commit();

		} catch (Exception ex) {
			tran.rollback();
			ex.printStackTrace();
		} finally {
			client.release();
		}
	}

	private void patch(DatabaseClient client, String uri, String path, String value, Transaction tran) {

		JSONDocumentManager jsonMgr = client.newJSONDocumentManager();

		DocumentPatchBuilder patchBuilder = jsonMgr.newPatchBuilder().pathLanguage(PathLanguage.JSONPATH);
		patchBuilder.replaceFragment(path, value);
		PatchHandle patchHandle = patchBuilder.build();

		jsonMgr.patch(uri, patchHandle, tran);
	}

	private DatabaseClient createDatabaseClient() {
		//réduction
	}
}

c'est tout

Recommended Posts

[Mark Logic] CRUD + α par "Java Client API"
Paramètre de délai d'expiration de l'API du client HTTP Java
Intégration API de Java avec Jersey Client
API Java Stream
Client Java mqtt
Générer du code client Java pour l'API SOAP de SalesForce
Emballez la réponse de l'API (java)
[Java] API / carte de flux
Dépannage de l'API Java Docker-Client
Pratique de l'API Java8 Stream
API Zabbix en Java
Programme Java qui récupère les journaux de travaux ESS avec l'API Web