Using Python to Operate MarkLogic
To operate the MarkLogic database using Python, you need to use MarkLogic's official Python client library - 'MarkLogic Python Client' This library can be installed through pip. Now let's gradually introduce how to use it to connect and operate MarkLogic databases.
###Connect to the MarkLogic database
Firstly, you need to import the 'DatabaseClient' class from the 'marklogic' library and create a database client using the host name, port, username, and password. For example:
python
from marklogic import DatabaseClient
Host='localhost' # MarkLogic host name
Port=8000 # MarkLogic Port
Username='admin' # username
Password='password' # Password
client = DatabaseClient(host, port, username, password)
###Data insertion
To insert data into the MarkLogic database, you need to use the database client's' new '_ The document 'method creates a new document object and uses' add'_ The content 'method adds the content to be stored. Then, use the 'write' method to write the document to the database. For example:
python
#Create a new document
doc = client.new_document()
#Add Content
doc.add_content('{"name": "John", "age": 30}')
#Write document to database
doc_uri = '/people/john.json'
client.write(doc, doc_uri)
###Data Query
To query data in the MarkLogic database, you can use the 'search' method on the database client. You need to specify a query string and specify the format of the results. Then, use the 'results' attribute to obtain the query results. For example:
python
query = 'John'
Result_ Format='JSON '# Specify the result format as JSON
results = client.search(query, result_format)
for result in results:
print(result)
###Data modification
To modify the data in the MarkLogic database, you can use the 'new' option on the database client_ The document 'method creates a new document object and uses' add'_ The content 'method adds the content to be modified. Then, use the 'write' method to write the updated document to the database. For example:
python
doc = client.new_document()
Doc.add_ Content ('{"name": "John Doe", "age": 35} ') # Update content
doc_uri = '/people/john.json'
client.write(doc, doc_uri)
###Data deletion
To delete data from the MarkLogic database, you can use the 'delete' method on the database client. You need to specify the document URI to delete. For example:
python
doc_uri = '/people/john.json'
client.delete(doc_uri)
These are basic operations, and you can perform more advanced operations according to your needs. Please refer to the official documentation of MarkLogic Python Client( https://developer.marklogic.com/products/python-client-api/8.0 )To obtain more detailed information.