Project

General

Profile

1
package edu.ucsb.nceas.metacat.index;
2

    
3
import org.apache.solr.client.solrj.SolrQuery;
4
import org.apache.solr.client.solrj.SolrServer;
5
import org.apache.solr.client.solrj.SolrServerException;
6
import org.apache.solr.client.solrj.impl.HttpSolrServer;
7
import org.apache.solr.client.solrj.response.QueryResponse;
8
import org.apache.solr.common.SolrDocument;
9
import org.apache.solr.common.SolrDocumentList;
10
import org.apache.solr.common.SolrInputDocument;
11

    
12
import java.io.IOException;
13
import java.util.Map;
14

    
15
public class SolrjIndex implements GenericIndex {
16
	protected SolrServer solr = null;
17

    
18
	SolrjIndex(String uri) {
19
		this.solr = new HttpSolrServer(uri);
20
	}
21

    
22
	public void insert(String docID, Map<String, String[]> fields) throws IOException {
23
		this.update(docID, fields);
24
	}
25

    
26
	public void update(String docID, Map<String, String[]> fields) throws IOException {
27
		SolrInputDocument doc = new SolrInputDocument();
28
		doc.addField(MetacatIndex.MCIDFIELD, docID);
29
		for (String k : fields.keySet()) {
30
			for (String v : fields.get(k)) {
31
				doc.addField(k, v);
32
			}
33
		}
34
		try {
35
			this.solr.add(doc);
36
		} catch (SolrServerException e) {
37
			e.printStackTrace();
38
		}
39
	}
40

    
41
	public void remove(String docID) throws IOException {
42
		try {
43
			solr.deleteByQuery(MetacatIndex.MCIDFIELD + ":" + docID);
44
		} catch (SolrServerException e) {
45
			// TODO: handling
46
			e.printStackTrace();
47
		}
48
	}
49

    
50
	public String[] query(String q) {
51
		SolrQuery sq = new SolrQuery(q);
52
		QueryResponse rsp = null;
53
		try {
54
			rsp = solr.query(sq);
55
		} catch (SolrServerException e) {
56
			// TODO: handling
57
			e.printStackTrace();
58
		}
59
		SolrDocumentList docs = rsp.getResults();
60
		String[] docIDs = new String[docs.size()];
61
		int i = 0;
62
		for (SolrDocument d : docs) {
63
			docIDs[i++] = d.getFieldValue(MetacatIndex.MCIDFIELD).toString();
64
		}
65
		return docIDs;
66
	}
67
}
(13-13/14)