Solr簡單使用

1.添加索引

		// 第一步:把solrJ的jar包添加到工程中。
		// 第二步:建立一個SolrServer,使用HttpSolrServer建立對象。
		SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
		// 第三步:建立一個文檔對象SolrInputDocument對象。
		SolrInputDocument document = new SolrInputDocument();
		// 第四步:向文檔中添加域。必須有id域,域的名稱必須在schema.xml中定義。
		document.addField("id", "test001");
		document.addField("item_title", "測試商品");
		document.addField("item_price", "199");
		// 第五步:把文檔添加到索引庫中。
		solrServer.add(document);
		// 第六步:提交。
		solrServer.commit();

2.刪除

		// 第一步:建立一個SolrServer對象。
		SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
		// 第二步:調用SolrServer對象的根據id刪除的方法。
		solrServer.deleteById("1");
		// 第三步:提交。
		solrServer.commit();

                  SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");java

                  solrServer.deleteByQuery("title:change.me");測試

                  solrServer.commit();xml


3.查詢

		SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
		// 第二步:建立一個SolrQuery對象。
		SolrQuery query = new SolrQuery();
		// 第三步:向SolrQuery中添加查詢條件、過濾條件。。。
		query.setQuery("*:*");
		// 第四步:執行查詢。獲得一個Response對象。
		QueryResponse response = solrServer.query(query);
		// 第五步:取查詢結果。
		SolrDocumentList solrDocumentList = response.getResults();
		System.out.println("查詢結果的總記錄數:" + solrDocumentList.getNumFound());
		// 第六步:遍歷結果並打印。
		for (SolrDocument solrDocument : solrDocumentList) {
			System.out.println(solrDocument.get("id"));
			System.out.println(solrDocument.get("item_title"));
			System.out.println(solrDocument.get("item_price"));
		}
相關文章
相關標籤/搜索