引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
添加配置(application.yml)
#solrcloud配置
spring.data.solr.repositories.enabled: true
spring.data.solr.zk-host: 10.10.2.137:2181,10.10.2.138:2181,10.10.2.139:2181
#單機配置
#spring.data.solr.host: http://localhost:8080/solr
#spring.data.solr.core: collection1
添加solr對象
@Data
@Accessors(chain = true)
@SolrDocument(solrCoreName = "demo")
public class UserDto {
@Field("id")
private String userId;
@Field("address")
private String address;
@Dynamic //動態域
@Field("item_spec_*")
private Map<String,String> specMap;//最好將範型加上
}
solrCoreName爲對應collection名稱
添加Repository類
@Repository
public interface UserRepository extends SolrCrudRepository<UserDto, String> {
@Query(value="address:?0",fields ={"address"},filters = {"id:?0"})
public List<UserDto> findByPage(String searchTerm, Pageable Pageable);
}
通過?0獲取searchTerm的值,@Query中的value等於q查詢,filters等於fq查詢
- 基本查詢
q 查詢的關鍵字,此參數最爲重要,例如,q=id:1,默認爲q=:,
fl 指定返回哪些字段,用逗號或空格分隔,注意:字段區分大小寫,例如,fl= id,title,sort
start 返回結果的第幾條記錄開始,一般分頁用,默認0開始
rows 指定返回結果最多有多少條記錄,默認值爲 10,配合start實現分頁
sort 排序方式,例如id desc 表示按照 “id” 降序
wt (writer type)指定輸出格式,有 xml, json, php等
fq (filter query)過慮查詢,提供一個可選的篩選器查詢。返回在q查詢符合結果中同時符合的fq條件的查詢結果,例如:q=id:1&fq=sort:[1 TO 5],找關鍵字id爲1 的,並且sort是1到5之間的。
df 默認的查詢字段,一般默認指定。
qt (query type)指定那個類型來處理查詢請求,一般不用指定,默認是standard。
indent 返回的結果是否縮進,默認關閉,用 indent=true|on 開啓,一般調試json,php,phps,ruby輸出纔有必要用這個參數。
version 查詢語法的版本,建議不使用它,由服務器指定默認值。
- Solr的檢索運算符
“:” 指定字段查指定值,如返回所有值*😗
“?” 表示單個任意字符的通配
“” 表示多個任意字符的通配(不能在檢索的項開始使用或者?符號)
“~” 表示模糊檢索,如檢索拼寫類似於”roam”的項這樣寫:roam將找到形如foam和roams的單詞;roam0.8,檢索返回相似度在0.8以上的記錄。
AND、|| 布爾操作符
OR、&& 布爾操作符
NOT、!、-(排除操作符不能單獨與項使用構成查詢)
“+” 存在操作符,要求符號”+”後的項必須在文檔相應的域中存在²
( ) 用於構成子查詢
[] 包含範圍檢索,如檢索某時間段記錄,包含頭尾,date:[201507 TO 201510]
{} 不包含範圍檢索,如檢索某時間段記錄,不包含頭尾date:{201507 TO 201510}
添加Service類
@Service
public class UserService {
@Resource
UserRepository userRepository;
public void save(UserDto userDto){
userRepository.save(userDto);
}
//查找第一頁的數據,按ID升序排序
public List<UserDto> queryByPage(String search){
Pageable pageable = PageRequest.of(0,3,new Sort(Sort.Direction.ASC, "id"));
return userRepository.findByPage(search,pageable);
}
}
添加controller方法(測試)
@RestController
public class SolrController {
@Autowired
private UserService userService;
@RequestMapping("/add/{id}")
public String add(@PathVariable String id,@RequestBody String address){
userService.save(new UserDto().setUserId(id).setAddress(address));
return id;
}
@RequestMapping("/query")
public String query(@RequestBody String address){
List<UserDto> list = userService.queryByPage(address);
return JSON.toJSONString(list);
}
}
高亮查詢
public List<Item> queryHeightLight(String address){
List<Item> itemList = new ArrayList<>();
HighlightQuery highlightQuery = new SimpleHighlightQuery(new SimpleStringCriteria("address:開平"));
HighlightOptions options = new HighlightOptions();
options.addField("address");
options.setSimplePrefix("<br>");
options.setSimplePostfix("</br>");
highlightQuery.setHighlightOptions(options);
HighlightPage<Item> page = solrTemplate.queryForHighlightPage("demo",highlightQuery,Item.class);
//獲取高亮數據
List<HighlightEntry<Item>> highlighted = page.getHighlighted();
for (HighlightEntry<Item> itemHighlightEntry : highlighted) {
//獲取SKU信息
Item item = itemHighlightEntry.getEntity();
//獲取高亮數據
List<HighlightEntry.Highlight> highlights = itemHighlightEntry.getHighlights();
//高亮數據
if(highlights!=null && highlights.size()>0 && highlights.get(0).getSnipplets()!=null
&& highlights.get(0).getSnipplets().size()>0){
String snipplets = highlights.get(0).getSnipplets().get(0);
//替換高亮數據
item.setTitle(snipplets);
itemList.add(item);
}
}
return itemList;
}
創建文件索引
/**
* 創建文件索引
*/
public void upFile(){
userRepository.deleteAll();
ContentStreamUpdateRequest up = new ContentStreamUpdateRequest(
"/update/extract");
File file = new File("C:/Users/Administrator/Desktop/demo/test.txt");
try{
up.addFile(file,"text/plain");
up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
CloudSolrClient solrClient = ((CloudSolrClient)solrTemplate.getSolrClient());
solrClient.setDefaultCollection("demo");
solrClient.request(up);
QueryResponse query = solrClient.query(new SolrQuery("*:*"));
SolrDocumentList results = query.getResults();
System.out.println(results);
}catch (Exception e){
}
}