正 文

在ASP应用程序中加入智能搜索


www.7dspace.com  更新日期:2005-9-28 1:54:22  七度空间


   在上面的代码中,有一个自定义函数 AutoKey ,该函数是实现智能搜索的核心所在。代码如下:

<%
Function AutoKey(strKey)
CONST lngSubKey=2
Dim lngLenKey, strNew1, strNew2, i, strSubKey

  检测字符串的合法性,若不合法则转到出错页。出错页你可以根据需要进行设定。

if InStr(strKey,"=")<>0 or InStr(strKey,"`")<>0 or InStr(strKey,"")<>0 or InStr(strKey," ")<>0 or InStr(strKey," ")<>0 or InStr(strKey,"")<>0 or InStr(strKey,chr(34))<>0 or InStr(strKey,"\")<>0 or InStr(strKey,",")<>0 or InStr(strKey,"<")<>0 or InStr(strKey,">")<>0 then
Response.Redirect "error.htm"
End If

lngLenKey=Len(strKey)
Select Case lngLenKey
Case 0 若为空串,转到出错页
Response.Redirect "error.htm"
Case 1 若长度为1,则不设任何值
strNew1=""
strNew2=""
Case Else 若长度大于1,则从字符串首字符开始,循环取长度为2的子字符串作为查询条件
For i=1 To lngLenKey-(lngSubKey-1)
strSubKey=Mid(strKey,i,lngSubKey)
strNew1=strNew1 & " or U_Name like %" & strSubKey & "%"
strNew2=strNew2 & " or U_Info like %" & strSubKey & "%"
Next
End Select

  得到完整的SQL语句

AutoKey="Select * from T_Sample where U_Name like %" & strKey & "% or U_Info like %" & strKey & "%" & strNew1 & strNew2

End Function
%>

  要实现智能搜索,其核心就是将搜索关键字进行自动分组。在此处,我们使用了循环取长度为2的子串的方法。为什么不将子串长度定为1、3、4或其他呢?这是因为若子串长度小于2即为1时,会失去将关键字分组的功能,而若子串长度大于2,则会丢失一些词组。大家可以将 CONST lngSubKey=2改为其他数字试一试,孰优孰劣自见分晓。

  最后,别忘了将数据连接关闭,以释放资源。

<%
CNN.Close
Set CNN=Nothing
%>

  至此,这个智能搜索引擎已经完成了。你还可以将其继续完善,比如添加分页、突出显示等功能。好了,不耽误大家时间了,赶快去试一试吧。

2页,页码:[1]  [2] 

上一篇:Ajax在.NET中与Server控件的交互
下一篇:XML Schema 中空值的表示
作者:  来源:中国编程网 ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐