【Sesame】Triple Store 添加三元數據

打算寫一個sesame數據庫的使用系列文章。這是第二篇,第一篇詳見這裏,講解sesame數據庫的搭建。

Sesame數據庫添加triple三元組的方法有很多種,這裏講解兩種,即單條添加與批量添加。

1. 建立數據庫鏈接

Sesame數據庫提供了幾種數據存儲辦法,有本地數據庫NativeStore,有基於內存的MemoryStore,有基於遠程數據庫的HTTP方式,還有基於關係型數據庫存儲方式的MySQLStore.

聲明變量:
private Repository repo;
	private MemoryStore memStore;
	private NativeStore natStore;
	private File repoFile;
	private RepositoryConnection repoConn;

基於內存MemoryStore:
	/**
	 * To get the repository within memory.
	 */
	public RepoUtil() {
		repoFile = new File(Const.repoPath);
		memStore = new MemoryStore();
		repo = new SailRepository(memStore);
	}


基於本地NativeStore:
	/**
	 * To get the repository on the disk.
	 * @param repoPath the repository file path
	 */
	public RepoUtil(String repoPath) {
		repoFile = new File(repoPath);
		natStore = new NativeStore(repoFile);
		repo = new SailRepository(natStore);
	}

基於網絡HTTP Connection:
	/**
	 * To get the repository on the Http server.
	 * @param server the server address
	 * @param repoId the repository ID
	 */
	public RepoUtil(String server, String repoId) {
		repo = new HTTPRepository(server, repoId);
	}

基於關係型數據庫MySQL:
參考我的另一篇文章.

1.1. 初始化數據庫

try {
			repo.initialize();
			repoConn = repo.getConnection();//Get the connection from repository connection pool
//			repoConn.setAutoCommit(false);//why deprecate the setAutoCommit method?
		} catch(RepositoryException e) {
			e.printStackTrace();
		}


2. 添加單條數據

2.1. 生成URI

此處提供函數用於生成URI,不需要如此麻煩,領會URI生成方法要領即可。
先需要初始化URI、Literal生成器ValueFactory:
ValueFactory valueFactory = new ValueFactoryImpl();

接下來即可生成URI:
	/**
	 * To get the URI of the specific string value
	 * 1. if it is already a URI, then return;
	 * 2. else translate it to URI format and return.
	 * @param iden
	 * @return the true URI
	 */
	public URI getUri(String iden) {
		URI rtn = null;
		String url = null;
		StringBuilder strRtn = new StringBuilder(uriBuilder);
		if(isUri(iden)) {
			System.out.println("isUri");
			return valueFactory.createURI(iden);
		} else {
			try {
				url = URLEncoder.encode(iden,"utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			strRtn.append(url);
			rtn = valueFactory.createURI(strRtn.toString());
			return rtn;
		}
	}

此處附上判斷URI的函數(摘自網絡)
	/**
	 * To justify if the input string is 
	 * in the format of URI.
	 * @param obj
	 * @return
	 */
	public boolean isUri(String obj) {
		return obj.matches("(([a-zA-Z][0-9a-zA-Z+\\\\-\\\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\\\.\\\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\\\.\\\\-_!~*'()%]+)?");
//		return false;
	}

生成URI與Literal方法的簡化版(會忽略某些問題,建議採用以上函數):
URI creativeWork = vf.createURI(namespace+"CreativeWork");
Literal about = vf.createLiteral(namespace+"about#"+"SomeString");

在構建好Connection、URI以及Literal以後,即可插入三元組:
	/**
	 * The URI-URI-Literal format SPO record.
	 */
	public void addRecord(URI subj, URI pred, Literal obj) {
		try {
//			repoConn = repo.getConnection();
			repoConn.add(subj, pred, obj);
//			repoConn.close();
		} catch (RepositoryException e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * The URI-URI-URI format SPO record.
	 */
	public void addRecord(URI subj, URI pred, URI obj) {
		try {
//			repoConn = repo.getConnection();
			repoConn.add(subj, pred, obj);
//			repoConn.close();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
	}

3、批量導入數據

如果有大量數據已經在文件中保存,我們不需要人工編寫數據讀取、寫入的代碼,直接通過Sesame已經提供的批量導入接口即可。
				File importFile = new File("segment"+j+".ttl");
				String baseURI = "http://rk.com/import/test/";
				RepositoryConnection con;
				try {
					FileReader fileReader = new FileReader(importFile);
					BufferedReader reader = new BufferedReader(fileReader);
					con = repo.getConnection();
					con.add(reader, baseURI, RDFFormat.TURTLE);
					System.out.println("Add "+j+" ends.");

					con.close();
				} catch (RepositoryException e) {
					e.printStackTrace();
				} catch (RDFParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} 

注意Java Heap的內存大小限制。
可以查看這裏修改Java虛擬機內存限制。

至此完成了Sesame數據寫入的幾種方法。
下回介紹數據導出與數據修改。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章