SimpleSolrQueryUtil.java 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.yihu.ehr.profile.util;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.springframework.util.StringUtils;
  4. import java.text.DateFormat;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Calendar;
  7. import java.util.Date;
  8. import java.util.Map;
  9. /**
  10. * Created by progr1mmer on 2018/3/26.
  11. */
  12. public class SimpleSolrQueryUtil {
  13. private static ObjectMapper objectMapper = new ObjectMapper();
  14. /**
  15. *
  16. * @param filter 要追加的参数 org_code=49229004X 多个条件用;分隔
  17. * @param date 时间类型 {"start":"2018-01-01T00:00:00Z","end":"2018-02-01T00:00:00Z","month":"2018-03"}
  18. * @param q 基础参数 {"q":"*:*"}
  19. * @return
  20. * @throws Exception
  21. */
  22. public static String getQuery(String filter, String date, String q) throws Exception {
  23. Map<String, String> qMap = objectMapper.readValue(q, Map.class);
  24. String param = qMap.get("q");
  25. if (!StringUtils.isEmpty(filter)) {
  26. String [] conditions = filter.split(";");
  27. for (String condition : conditions) {
  28. if (condition.split("=").length == 2) {
  29. String key = condition.split("=")[0];
  30. String value = condition.split("=")[1];
  31. param += " AND " + key + ":" + value;
  32. }
  33. if (condition.split("\\?").length == 2) {
  34. String key = condition.split("\\?")[0];
  35. String value = condition.split("\\?")[1];
  36. param += " AND " + key + ":*" + value + "*";
  37. }
  38. continue;
  39. }
  40. }
  41. if (!StringUtils.isEmpty(date)) {
  42. Map<String, String> dateMap = objectMapper.readValue(date, Map.class);
  43. if (!StringUtils.isEmpty(dateMap.get("start"))) {
  44. param += " AND event_date:[" + dateMap.get("start") + " TO *]";
  45. }
  46. if (!StringUtils.isEmpty(dateMap.get("end"))) {
  47. param += " AND event_date:[* TO " + dateMap.get("end") + "]";
  48. }
  49. if (!StringUtils.isEmpty(dateMap.get("month"))) {
  50. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
  51. Date date1 = dateFormat.parse(dateMap.get("month"));
  52. Calendar calendar = Calendar.getInstance();
  53. calendar.setTime(date1);
  54. String start = dateMap.get("month") + "-01T00:00:00Z";
  55. int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  56. String end = dateMap.get("month") + "-" + maxDay + "T00:00:00Z";
  57. param += " AND event_date:[" + start + " TO " + end + "]";
  58. }
  59. }
  60. String sort = "{\"event_date\":\"desc\"}";
  61. qMap.put("sort", sort);
  62. qMap.put("q", param);
  63. return objectMapper.writeValueAsString(qMap);
  64. }
  65. }