[MarkLogic] CRUD + α by "Java Client API"

Introduction

I have written the code to CRUD the data (JSON) on MarkLogic using the "Java Client API".

environment

CRUD

Basic CRUD.

Document Create

Create a new document. Let MarkLogic handle the generation of the document URI.

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();
		//Specify extension
		DocumentUriTemplate uriTemplate = docMgr.newDocumentUriTemplate("json");
		//Specify directory
		uriTemplate.setDirectory("/xxx/yyy/");

		DocumentDescriptor desc = docMgr.create(uriTemplate, new StringHandle(jsonData), tran);
		//Return document URI to caller
		return desc.getUri();
	}

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

Document Search & Read

A QBE search identifies the URI and loads the 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); //Default 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() {
		//abridgement
	}
}

Document Search & Update (Update)

The QBE search identifies the URI and updates (overwrites) the 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) {
		//abridgement
	}

	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() {
		//abridgement
	}
}

Document Search & Delete

A QBE search identifies the URI and deletes the 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) {
		//abridgement
	}

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

	private DatabaseClient createDatabaseClient() {
		//abridgement
	}
}

Update only part of the document.

Partial update of document (update value)

Specify the path in the document to update the value.

Value update


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() {
		//abridgement
	}
}

Partial update of document (added to array element)

Add an element to the end of the array element.

Add to array element


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() {
		//abridgement
	}
}

Partial update of document (replace array elements)

Replaces the contents of the array elements completely.

Replace array elements


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() {
		//abridgement
	}
}

that's all

Recommended Posts

[MarkLogic] CRUD + α by "Java Client API"
Java HTTP Client API timeout setting
API integration from Java with Jersey Client
Java Stream API
Java mqtt client
Generate Java client code for Salesforce SOAP API
Pack API response (java)
[Java] Stream API / map
Docker-Client Java API Troubleshooting
Java8 Stream API practice
Zabbix API in Java
Java program to get ESS Job log by Web API