수색…


소개

Suitescript 2.0은 검색 결과를 처리하는 4 가지 방법을 제공합니다.

이들은 구문, 제한 사항 및 거버넌스가 다르며 상황에 따라 적절합니다. 여기에서는 각각의 방법을 사용하여 모든 검색 결과에 액세스하는 방법에 초점을 맞출 것입니다.

Search.ResultSet.each 메서드 사용

이것은 가장 짧고 쉽고 가장 일반적으로 사용되는 방법입니다. 유감스럽게도 한 가지 중요한 한계가 있습니다. 4000 개가 넘는 결과 (행)가있는 검색에는 사용할 수 없습니다.

    // Assume that 'N/search' module is included as 'search'
    
    var s = search.create({
        type : search.Type.TRANSACTION,
        columns : ['entity','amount'],
        filters : [  ['mainline', 'is', 'T'],
              'and', ['type', 'is', 'CustInvc'],
              'and', ['status', 'is', 'open']
            ]
    });

    var resultSet = s.run();
    
    // you can use "each" method on searches with up to 4000 results    
    resultSet.each( function(result) {
        
        // you have the result row. use it like this....
        var transId = result.id;
        var entityId = result.getValue('entity'); 
        var entityName = result.getText('entity');
        var amount = result.getValue('amount');
        
        // don't forget to return true, in order to continue the loop
        return true;  

    });

ResultSet.getRange 메소드의 사용

많은 수의 결과를 처리하기 위해 getRange를 사용하려면 다음을 고려해야합니다.

  1. getRange에는 startend 라는 두 개의 매개 변수가 있습니다. 항상 긍정적 인, 항상 (시작 <끝)
  2. start 는 반환 할 첫 번째 결과의 포괄적 인 인덱스입니다.
  3. end 는 반환 할 마지막 결과의 배타 인덱스입니다.
  4. 요청 된 것보다 적은 수의 결과가있는 경우 배열에는 end - start 항목보다 적은 수의 항목이 포함됩니다. 예를 들어 25 개의 검색 결과 만있는 경우 getRange (20, 30)은 5 개의 search.Result 객체의 배열을 반환합니다.
  5. 위의 도움말 문장은 직접 말하지 않지만 시작 모두 사용 가능한 결과 범위를 벗어날 수 있습니다. 같은 예 - 검색 결과가 25 개 밖에없는 경우 getRange (100, 200)은 빈 배열 []을 반환합니다.
  6. 한 번에 최대 1000 개의 행. (끝 - 시작) <= 1000
    // Assume that 'N/search' module is included as 'search'
    
    // this search will return a lot of results (not having any filters) 
    var s = search.create({
        type: search.Type.TRANSACTION,
        columns : ['entity','amount'],
        filters: [] 
    });
    
    var resultSet = s.run();

    // now take the first portion of data.
    var currentRange = resultSet.getRange({
            start : 0,
            end : 1000
    });
    
    var i = 0;  // iterator for all search results
    var j = 0;  // iterator for current result range 0..999

    while ( j < currentRange.length ) {
        
        // take the result row
        var result = currentRange[j];
        // and use it like this....
        var transId = result.id;
        var entityId = result.getValue('entity'); 
        var entityName = result.getText('entity');
        var amount = result.getValue('amount');
        
        // finally:
        i++; j++;
        if( j==1000 ) {   // check if it reaches 1000
            j=0;          // reset j an reload the next portion
            currentRange = resultSet.getRange({
                start : i,
                end : i+1000
            });
        }
    }

거버넌스를 계산할 수 있습니다. 우리는 각각 10 단위를 취하는 1 + count / 1000 getRange 호출을가집니다.

G = (1 + 카운트 / 1000) * 10

예 : 9500 개의 행은 100 단위를 취합니다.

Search.PagedData.fetch 메서드 사용

PagedData는 Search.runPaged (options) 메소드에 의해 반환되는 객체입니다. 그것은 UI 검색이하는 것처럼 정확하게 작동합니다. PagedData 개체에는 Netsuite UI의 검색 결과 페이지에서 결과 머리글의 오른쪽에 볼 수있는 두 가지 중요한 속성이 있습니다.

  • count (결과의 총 수)
  • pageRanges (페이지 목록, UI에서 콤보 상자 선택자로 사용 가능)

options.pageSize 매개 변수는 다시 1000 개의 결과 행으로 제한됩니다.
PagedData.fetch 메서드는 원하는 결과 부분을 가져 오는 데 사용됩니다 (pageIndex 매개 변수로 인덱싱 됨). 조금 더 많은 코드를 사용하면 Search.ResultSet.each와 같은 편리한 콜백 함수를 4000 행 제한없이 사용할 수 있습니다.

    // Assume that 'N/search' module is included as 'search'

    // this search will return a lot of results (not having any filters)  
    var s = search.create({
        type: search.Type.TRANSACTION,
        columns : ['entity','amount'],
        filters : [] 
    });
    
    var pagedData = s.runPaged({pa​g​e​S​i​z​e : 1000});
    
    // iterate the pages
    for( var i=0; i < pagedData.pageRanges.length; i++ ) {

        // fetch the current page data
        var currentPage = pagedData.fetch(i);

        // and forEach() thru all results
        currentPage.data.forEach( function(result) {

            // you have the result row. use it like this....
            var transId = result.id;
            var entityId = result.getValue('entity'); 
            var entityName = result.getText('entity');
            var amount = result.getValue('amount');

        });

    }

거버넌스를 계산할 수 있습니다. 우리는 runPaged ()를위한 5 유닛과 각각 5 유닛을 취하는 1 + count / 1000 pagedData.fetch 호출을 가지고 있습니다 :

G = 5 + ceil (count / 1000) * 5

예 : 9500 개의 행은 55 개의 단위를 사용합니다. getRange 거버넌스 유닛의 약 절반.

전용 맵 / 축소 스크립트 사용

정말 큰 검색 결과를 얻으려면 전용 Map / Reduce 스크립트를 사용할 수 있습니다. 훨씬 더 불편하지만 때로는 피할 수없는 경우가 있습니다. 때로는 매우 편리 할 수 ​​있습니다.
트릭은 입력 데이터 가져 오기 단계에서 NS 엔진에 실제 데이터 (예 : 스크립트 결과)가 아닌 검색 정의 만 제공 할 수 있다는 것입니다. NS는 거버넌스 단위를 세지 않고 검색을 수행합니다. 그런 다음 각각의 단일 결과 행이 맵 스테이지로 전달됩니다.
물론 제한 사항이 있습니다.지도 / 축소 스크립트의 지속 된 전체 데이터 크기는 50MB를 초과 할 수 없습니다. 검색 결과에서 각 값과 각 키의 직렬화 된 크기가 전체 크기로 계산됩니다. "Serialized"는 JSON.stringify를 사용하여 검색 결과 행을 문자열로 변환한다는 의미입니다. 따라서 값 크기는 결과 집합의 검색 결과 열 수에 비례합니다. STORAGE_SIZE_EXCEEDED 오류로 문제가 발생하는 경우 열 축소, 수식 결합, 결과 그룹화 또는 여러 하위 검색으로 검색 분할 (지도 또는 축소 단계에서 실행될 수 있음)을 고려해보십시오.

    /**
     * @NApiVersion 2.0
     * @NScriptType MapReduceScript
     */
    define(['N/search'], function(search) {

    function getInputData()
    {
        return search.create({
            type: search.Type.TRANSACTION,
            columns : ['entity','amount'],
            filters : [] 
        });
    }

    function map(context)
    {
        var searchResult = JSON.parse(context.value);
        // you have the result row. use it like this....
        var transId = searchResult.id;
        var entityId = searchResult.values.entity.value;
        var entityName = searchResult.values.entity.text;
        var amount = searchResult.values.amount.value;
        
        // if you want to pass some part of the search result to the next stage
        // write it to context:
        context.write(entityId, transId);
    }

    function reduce(context)
    {
       // your code here ...
    }

    function summarize(summary)
    {
        // your code here ...
    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});

물론 여기의 예제는 오류 처리없이 단순화되어 다른 것과 비교하기 위해 제공됩니다. NS 도움말 센터의지도 / 축소 스크립트 유형 예제에서 더 많은 예제를 볼 수 있습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow